Linux環境下用C語言實現socket 通信---簡單代碼


Socket編程實例:

服務器端:一直監聽本機的8000號端口,如果收到連接請求,將接收請求並接收客戶端發來的消息,並向客戶端返回消息。

客戶端:client.c

 1 /* File Name: client.c */  
 2   
 3 #include<stdio.h>  
 4 #include<stdlib.h>  
 5 #include<string.h>  
 6 #include<errno.h>  
 7 #include<sys/types.h>  
 8 #include<sys/socket.h>  
 9 #include<netinet/in.h>  
10   
11 #define MAXLINE 4096  
12   
13   
14 int main(int argc, char** argv)  
15 {  
16     int    sockfd, n,rec_len;
17     int     i_port = 8000; //默認8000端口
18     
19     char    recvline[4096], sendline[4096];  
20     char    buf[MAXLINE];  
21     char   *c_ipAddr = "127.0.0.1";
22     
23     struct sockaddr_in    servaddr;      
24   
25     if( argc == 1)
26     {
27         printf("This client will connect server message: IP=127.0.0.1 , Port=8000 \n");        
28     }
29     else if( argc ==2 )
30     {
31         c_ipAddr = argv[1];
32         printf("This client will connect server message: IP=%s , Port=8000 \n",c_ipAddr);    
33     }
34     else if( argc == 3)
35     {
36         c_ipAddr = argv[1];    
37         i_port = atoi(argv[2]);
38         printf("This client will connect server message: IP=%s , Port=%d \n",c_ipAddr, i_port);    
39     }
40     else
41     {  
42         printf("usage: ./client <ipaddress> and port \n");  
43         exit(0);  
44     }  
45   
46       
47     if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){  
48     printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);  
49     exit(0);  
50     }  
51   
52   
53     memset(&servaddr, 0, sizeof(servaddr));  
54     servaddr.sin_family = AF_INET;  
55     servaddr.sin_port = htons(i_port);  
56     
57     if( inet_pton(AF_INET, c_ipAddr, &servaddr.sin_addr) <= 0){  
58     printf("inet_pton error for %s\n",argv[1]);  
59     exit(0);  
60     }  
61   
62   
63     if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){  
64     printf("connect error: %s(errno: %d)\n",strerror(errno),errno);  
65     exit(0);  
66     }  
67   
68   
69     printf("send msg to server: \n");  
70     fgets(sendline, 4096, stdin);  
71     if( send(sockfd, sendline, strlen(sendline), 0) < 0)  
72     {  
73     printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);  
74     exit(0);  
75     }  
76     if((rec_len = recv(sockfd, buf, MAXLINE,0)) == -1) {  
77        perror("recv error");  
78        exit(1);  
79     }  
80     buf[rec_len]  = '\0';  
81     printf("Received : %s ",buf);  
82     close(sockfd);  
83     exit(0);  
84 }  

服務端:server.c

 1 /* File Name: server.c */  
 2 #include<stdio.h>  
 3 #include<stdlib.h>  
 4 #include<string.h>  
 5 #include<errno.h>  
 6 #include<sys/types.h>  
 7 #include<sys/socket.h>  
 8 #include<netinet/in.h>  
 9 
10 
11 #define DEFAULT_PORT 8000  //監聽端口號
12 #define MAXLINE 4096  
13 int main(int argc, char** argv)  
14 {  
15     int    socket_fd, connect_fd;  
16     struct sockaddr_in     servaddr;  
17     char    buff[4096];  
18     int     n;  
19     //初始化Socket  
20     if( (socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){  
21     printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);  
22     exit(0);  
23     }  
24     //初始化  
25     memset(&servaddr, 0, sizeof(servaddr));  
26     servaddr.sin_family = AF_INET;  
27     servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//IP地址設置成INADDR_ANY,讓系統自動獲取本機的IP地址。  
28     servaddr.sin_port = htons(DEFAULT_PORT);//設置的端口為DEFAULT_PORT  
29   
30     //將本地地址綁定到所創建的套接字上  
31     if( bind(socket_fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){  
32     printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);  
33     exit(0);  
34     }  
35     //開始監聽是否有客戶端連接  
36     if( listen(socket_fd, 10) == -1){  
37     printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);  
38     exit(0);  
39     }  
40     printf("======waiting for client's request======\n");  
41     while(1){  
42 //阻塞直到有客戶端連接,不然多浪費CPU資源。  
43         if( (connect_fd = accept(socket_fd, (struct sockaddr*)NULL, NULL)) == -1){  
44         printf("accept socket error: %s(errno: %d)",strerror(errno),errno);  
45         continue;  
46     }  
47 //接受客戶端傳過來的數據  
48     n = recv(connect_fd, buff, MAXLINE, 0);  
49 //向客戶端發送回應數據  
50     if(!fork()){ /*子進程*/  
51         if(send(connect_fd, "Hello,you are connected!\n", 26,0) == -1)  
52         perror("send error");  
53         close(connect_fd);  
54         exit(0);  
55     }  
56     buff[n] = '\0';  
57     printf("recv msg from client: %s\n", buff);  
58     close(connect_fd);  
59     }  
60     close(socket_fd);  
61 }  

編譯:

  客戶端 gcc -o client client.c

  服務端 gcc -o server server.c

 

運行:(倆個窗口運行,一個服務端一個客戶端)

  服務端 ./server

  客戶端  有3種運行方式

      1.  ./client (無ip無端口 使用默認的  IP=127.0.0.1 , Port=8000 地址 )

            

      2.  ./client  192.168.109.133   (添加ip 無端口 使用默認端口 8000)

         

      3.   ./client  192.168.109.133 10101 (使用指定的ip和端口)

         

演示:默認方式

  客戶端:

      

  服務端:

       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM