//服务器
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <arpa/inet.h>
5 #include <unistd.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #define SERV_IP "127.0.0.1" //本机IP
10 #define SERV_PORT 8000
11
12 void process_cli(int conn_fd, struct sockaddr_in client);
13 void sys_err(char* err)
14 {
15 perror(err);
16 exit(1);
17 }
18 int main(void)
19 {
20 int sock_fd;
21 int conn_fd;
22 int ret;
23 socklen_t addrlen;
24 int len;
25 pid_t pid;
26
27 struct sockaddr_in cli_addr;
28 struct sockaddr_in serv_addr;
29
30 memset(&serv_addr, 0, sizeof(serv_addr));
31 serv_addr.sin_family = AF_INET;
32 serv_addr.sin_port = htons(SERV_PORT);
33 inet_pton(AF_INET, SERV_IP, &serv_addr.sin_addr.s_addr);
34
35 sock_fd = socket(AF_INET, SOCK_STREAM, 0);
36 if(sock_fd == -1)
37 sys_err("fail to socket");
38
39 int opt = SO_REUSEADDR;
40 setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
41 ret = bind(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
42 if(ret == -1)
43 sys_err("fail to bind");
44
45 ret = listen(sock_fd, 20);
46 if(ret == -1)
47 sys_err("fail to listen");
48
49
50 char buf[1024];
51 int readsize;
52 while(1)
53 {
54 if((conn_fd = accept(sock_fd, (struct sockaddr*)&cli_addr, &len)) == -1)
55 sys_err("fail to connect");
56 if((pid = fork()) > 0)
57 {
58 close(conn_fd);
59 continue;
60 }
61 else if(pid == 0)
62 {
63 close(sock_fd);
64 process_cli(conn_fd, cli_addr);
65 exit(0);
66 }
67 else
68 {
69 printf("fork() error");
70 exit(0);
71 }
72 }
73
74 close(sock_fd);
75
76 return 0;
77 }
78
79
80 void process_cli(int conn_fd, struct sockaddr_in client)
81 {
82
83 int num;
84 char buf[1024];
85
86 printf("You got a connection from %s. ", inet_ntoa(client.sin_addr));
87
88 while(num = recv(conn_fd, buf, 1024, 0))
89 {
90 buf[num] = '/0';
91
92 printf("%s", buf);
93
94 }
95
96
97 printf("The client <%s> exit. ", inet_ntoa(client.sin_addr));
98 close(conn_fd);
99 }
//客户端
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <arpa/inet.h>
4 #include <sys/socket.h>
5 #include <sys/types.h>
6 #include <stdlib.h>
7 #include <string.h>
8
9 #define SERV_IP "127.0.0.1"
10 #define SERV_PORT 8000
11
12 void sys_err(char* err)
13 {
14 perror(err);
15 exit(0);
16 }
17 int main(void)
18 {
19 int sockfd;
20 int ret;
21
22 struct sockaddr_in serv_addr;
23 memset(&serv_addr, 0, sizeof(serv_addr));
24 serv_addr.sin_family = AF_INET;
25 serv_addr.sin_port = htons(SERV_PORT);
26 serv_addr.sin_addr.s_addr = inet_addr(SERV_IP);
27
28 sockfd = socket(AF_INET, SOCK_STREAM, 0);
29 if(sockfd == -1)
30 sys_err("fail to socket");
31 ret = connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
32 if(ret == -1)
33 sys_err("fail to connect");
34 char buf[1024];
35 int readsize;
36
37 while(1)
38 {
39 readsize = read(STDIN_FILENO, buf, 1024);
40 if(strncmp(buf, "exit", 4) == 0)
41 {
42 printf("client has exited");
43 break;
44 }
45
46 write(sockfd, buf, readsize);
47 }
48 close(sockfd);
49
50 }