1 #include <stdio.h>
2 #include <strings.h> //bzero
3 #include <unistd.h> //close
4 #include <sys/socket.h> //socket
5 #include <netinet/in.h> //struct sockaddr_in
6 #include <arpa/inet.h> //inet_addr
7 int main(int argc, char const *argv[])
8 {
9 // 1.创建套接字
10 int sockfd = socket(AF_INET, SOCK_STREAM, 0);
11 if (sockfd < 0)
12 {
13 perror("socket");
14 return -1;
15 }
16 // 2.绑定bind
17 struct sockaddr_in my_addr;
18 my_addr.sin_family = AF_INET;
19 my_addr.sin_port = htons(8000);
20 my_addr.sin_addr.s_addr = htonl(INADDR_ANY); // 机器的所有可用IP地址
21 int ret = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(my_addr));
22 if (ret != 0)
23 {
24 perror("bind");
25 return -1;
26 }
27 // 3.监听
28 int backlog = 10;
29 ret = listen(sockfd, backlog);
30 if (ret < 0)
31 {
32 perror("listen");
33 return -1;
34 }
35 // 4.提取,等待一个客户端连接
36 struct sockaddr_in cli_addr;
37 socklen_t len = sizeof(cli_addr);
38 int sockfd_new = accept(sockfd, (struct sockaddr *)&cli_addr, &len);
39 if (sockfd_new < 0)
40 {
41 perror("accept");
42 return -1;
43 }
44 // 5.接收数据
45 char buf[1024] = "";
46 char ip[16] = "";
47 while (1)
48 {
49 bzero(buf, sizeof(buf));
50 recv(sockfd_new, buf, sizeof(buf), 0);
51 inet_ntop(AF_INET, (void *)&cli_addr.sin_addr, ip, 16);
52 printf("%s:%hu--->%s\n", ip, ntohs(cli_addr.sin_port), buf); // ip port buf
53 send(sockfd_new, "ok", sizeof("ok"), 0); // 发送消息
54 }
55 // 6.关闭套接字
56 close(sockfd_new);
57 close(sockfd);
58 return 0;
59 }
![]()