server.c:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <strings.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 #define PORT 8888
11 #define BACKLOG 10
12
13 int main(int argc, char *argv[])
14 {
15 int listenfd, connectfd;
16 struct sockaddr_in server;
17 struct sockaddr_in client;
18 int sin_size;
19
20 if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
21 perror("Creating socket failed.");
22 exit(0);
23 }
24
25 int opt = SO_REUSEADDR;
26 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
27
28 bzero(&server, sizeof(server));
29 server.sin_family = AF_INET;
30 server.sin_port = htons(PORT);
31 server.sin_addr.s_addr = htonl(INADDR_ANY);
32
33 if (bind(listenfd, (struct sockaddr *)&server,
34 sizeof(struct sockaddr)) == -1){
35 perror("Bind error!");
36 exit(0);
37 }
38
39 if (listen(listenfd,BACKLOG) == -1){
40 perror("Listen error!");
41 exit(0);
42 }
43
44 while(1){
45 sin_size = sizeof(struct sockaddr_in);
46
47 if((connectfd = accept(listenfd, (struct sockaddr *)&client, &sin_size)) == -1) {
48 perror("Accept error!");
49 break;
50 }
51
52 printf("You got a connection from %s\n", inet_ntoa(client.sin_addr));
53
54 send(connectfd, "Fucking client!\n", 16, 0);
55
56 close(connectfd);
57 }
58
59 close(listenfd);
60 exit(0);
61 }
client.c:
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <strings.h>
4 #include <stdlib.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <netdb.h>
9
10 #define PORT 8888
11 #define MAXDATASIZE 100
12
13 int main(int argc, char *argv[])
14 {
15 int fd, numbytes;
16 char buf[MAXDATASIZE];
17 struct hostent *he;
18 struct sockaddr_in server;
19
20 if (argc != 2) {
21 printf("Usage: %s <IP Address>\n",argv[0]);
22 exit(0);
23 }
24
25 if((he = gethostbyname(argv[1])) == NULL) {
26 printf("gethostbyname() error\n");
27 exit(0);
28 }
29
30 if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
31 printf("socket() error\n");
32 exit(0);
33 }
34
35 bzero(&server, sizeof(server));
36 server.sin_family = AF_INET;
37 server.sin_port = htons(PORT);
38 server.sin_addr = *((struct in_addr *)he->h_addr);
39
40 if(connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) {
41 close(fd);
42 printf("Connect error!");
43 exit(0);
44 }
45
46 if((numbytes = recv(fd, buf, MAXDATASIZE, 0)) == -1) { /* calls recv() */
47 printf("Recv error!");
48 exit(0);
49 }
50
51 buf[numbytes] = '\0';
52 printf("Server Message: %s \n", buf);
53
54 close(fd);
55 }
编译:
1 gcc -o server server.c
2 gcc -o client client.c
运行:
1 # server端
2 ./server
3 # client端
4 ./client 127.0.0.1