基于Linux的服务器和客户端

server.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <unistd.h>
 5 #include <arpa/inet.h>
 6 #include <sys/socket.h>
 7 
 8 void error_handing(char *message);
 9 
10 int main(int argc, char *argv[])
11 {
12     int serv_sock;
13     int clnt_sock;
14 
15     struct sockaddr_in serv_addr;
16     struct sockaddr_in clnt_addr;
17     socklen_t clnt_addr_size;
18 
19     char message[] = "Hello World!";
20 
21     if(argc != 2)
22     {
23         printf("Usage : %s <port>\n", argv[0]);
24         exit(1);
25     }
26 
27     serv_sock = socket(PF_INET, SOCK_STREAM, 0);
28     if(serv_sock == -1)
29         error_handing("socket() error");
30 
31     memset(&serv_addr, 0, sizeof(serv_addr));
32     serv_addr.sin_family = AF_INET;
33     serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
34     serv_addr.sin_port = htons(atoi(argv[1]));
35 
36     if(bind(serv_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) == -1)
37         error_handing("bind() error");
38 
39     if(listen(serv_sock, 5) == -1)
40         error_handing("listen() error");
41 
42     clnt_addr_size = sizeof(clnt_addr);
43     clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
44     if(clnt_sock == -1)
45         error_handing("accept() error");
46 
47     write(clnt_sock, message, sizeof(message));
48     close(clnt_sock);
49     close(serv_sock);
50     return 0;
51 }
52 
53 void error_handing(char *message)
54 {
55     fputs(message, stderr);
56     fputc('\n', stderr);
57     exit(1);
58 }

client.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <unistd.h>
 5 #include <arpa/inet.h>
 6 #include <sys/socket.h>
 7 void error_handing(char *message);
 8 
 9 int main(int argc, char *argv[])
10 {
11     int sock;
12     struct sockaddr_in serv_addr;
13     char message[30];
14     int str_len;
15 
16     if(argc != 3)
17     {
18         printf("Usage : %s <IP> <port>\n", argv[0]);
19         exit(1);
20     }
21 
22     sock = socket(PF_INET, SOCK_STREAM, 0);
23     if(sock ==-1)
24         error_handing("socket() error");
25 
26     memset(&serv_addr, 0, sizeof(serv_addr));
27     serv_addr.sin_family = AF_INET;
28     serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
29     serv_addr.sin_port = htons(atoi(argv[2]));
30 
31     if(connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
32         error_handing("connect() error");
33 
34     str_len = read(sock, message, sizeof(message) - 1);
35     if(str_len == -1)
36         error_handing("read() error");
37     printf("Message from server : %s \n", message);
38     close(sock);
39     return 0;
40 }
41 
42 void error_handing(char *message)
43 {
44     fputs(message, stderr);
45     fputc('\n', stderr);
46     exit(1);
47 }

 

posted @ 2019-10-22 22:04  wisdomroc  阅读(737)  评论(0编辑  收藏  举报