client (1)

/* client.c */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
//#include "wrap.h"

#define MAXLINE 80
#define SERV_PORT 8000

int main(int argc, char *argv[])
{
 struct sockaddr_in servaddr;
 char buf[MAXLINE];
 int sockfd, n;
//AF_INET ipv4 地址族
 sockfd = socket(AF_INET, SOCK_STREAM, 0);

 bzero(&servaddr, sizeof(servaddr));
 servaddr.sin_family = AF_INET;
 //将字符串地址转换成二进制IP
 inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
 //转成网络字节,可能大小端不一样。
 servaddr.sin_port = htons(SERV_PORT);
//传进来指针和指向结构体地址大小,这是标准的做法
 connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

 while (fgets(buf, MAXLINE, stdin) != NULL) {
  write(sockfd, buf, strlen(buf));
  n = read(sockfd, buf, MAXLINE);
  if (n == 0)
   printf("the other side has been closed.\n");
  else
   write(STDOUT_FILENO, buf, n);
 }

 close(sockfd);
 return 0;
}

你可能感兴趣的:(client (1))