1 /*server.c*/
2 #include <stdio.h>
3 #include <arpa/inet.h>
4 #include <sys/types.h> /* See NOTES */
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #define err_log(errlog) do{ perror(errlog); exit(1);}while(0)
10 int main(int argc, const char *argv[])
11 {
12 int sockfd;
13 int acceptfd;
14 struct sockaddr_in serveraddr, clientaddr;
15
16 if (argc != 3)
17 {
18 fprintf(stderr,"Usage:%s serverip port.
", argv[0]);
19 return -1;
20 }
21 /*server端 第一步:socket 创建套接字*/
22 if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
23 {
24 err_log("fail to socket");
25 }
26 /*server端 第二步: 填充网络信息结构体*/
27 serveraddr.sin_family = AF_INET;
28 serveraddr.sin_addr.s_addr = inet_addr(argv[1]);//argv[1]:由手动输入,终端的第二个参数
29 serveraddr.sin_port = htons(atoi(argv[2]));//htons 将本地字节序变为网络字节序,atoi将数字类字符串转化为数字,如字符串“80” 变为数字80
30 /*server端 第三步 :bind() 绑定*/
31 if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
32 {
33 err_log("fail to bind");
34 }
35 /*server端 第四步:listen() 监听*/
36 if(listen(sockfd, 15) < 0)
37 {
38 err_log("fail to listen");
39 }
40
41 socklen_t addrlen = sizeof(struct sockaddr_in);
/*接收客户端的连接请求*/
42 acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen);
43
44 if(acceptfd < 0)
45 {
46 err_log("fail to acceptfd");
47 }
48
49 printf("%s --> %d
", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
/*inet_ntoa函数将网络字节序的IP地址转换为十进制的字符串*/
/*ntohs 将网络端口号转换为本地端口号*/
50 close(acceptfd); //关闭文件描述符
51 close(sockfd);//关闭文件描述符
52 return 0;
}
53
1 /*client*/
2 #include <stdio.h>
3 #include <arpa/inet.h>
4 #include <sys/types.h> /* See NOTES */
5 #include <sys/socket.h>
6 #include <netinet/in.h>
7 #include <stdlib.h>
8 #include <unistd.h>
9 #define err_log(errlog) do{ perror(errlog); exit(1);}while(0)
10
11 int main(int argc, const char *argv[])
12 {
13 int sockfd;
14 int acceptfd;
15 struct sockaddr_in serveraddr, clientaddr;
16
17 if(argc != 3)
18 {
19 fprintf(stderr,"Usage:%s serverip port.
", argv[0]);
20 return -1;
21 }
22 /*client端 第一步:socket套接字*/
23 if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
24 {
25 err_log("fail to socket");
26 }
27 /*client端 第二部:填充网络信息结构体*/
28 serveraddr.sin_family = AF_INET;
29 serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
30 serveraddr.sin_port = htons(atoi(argv[2]));
31 /*client端 第三步:连接服务器端*/
32 if(connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
33 {
34 err_log("fail to connect");
35 }
36 close(sockfd);//关闭文件描述符
37 return 0;
38 }