Linux C語言實現的Socket通訊 good

來源:互聯網
上載者:User

Linux C語言實現的Socket通訊 - Chris_Home - 部落格頻道 - CSDN.NET

Linux C語言實現的Socket通訊 分類: Linux 2011-12-19 00:24 630人閱讀 評論(0) 收藏 舉報socketlinuxc語言structdescriptor

其實這篇文章就是前面一篇文章的複製體,主要是今天閑著無聊,就在Ubuntu下又寫了一篇這個傳說中的簡單Socket通訊。

 

以下是Linux網路編程的函數說明

'socket' Function
To perform network I/O, the first thing a process must do is call the socket function,
specifying the type of communication protocol desired (TCP using IPv4, UDP using
IPv6, Unix domain stream protocol, etc.).
#include <sys/socket.h>
int socket (int family, int type, int protocol);
Returns: non-negative descriptor if OK, -1 on error
    

具體參數如下

'connect' Function
The connect function is used by a TCP client to establish a connection with a TCP
server.
#include <sys/socket.h>
int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);
Returns: 0 if OK, -1 on error
其中struct sockaddr
是一個結構體。
struct sockaddr_in { sa_family_t sin_family; /* address family: AF_INET */ in_port_t sin_port; /* port in network byte order */ struct in_addr sin_addr; /* internet address */};/* Internet address. */struct in_addr { uint32_t s_addr; /* address in network byte order */};

'bind' Function
#include <sys/socket.h>
int bind (int sockfd, const struct sockaddr *myaddr, socklen_t addrlen);
Returns: 0 if OK,-1 on error

'listen' Function
#include <sys/socket.h>
#int listen (int sockfd, int backlog);
Returns: 0 if OK, -1 on error

'accept' Function
#include <sys/socket.h>
int accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
Returns: non-negative descriptor if OK, -1 on error

This function returns up to three values: an integer return code that is either a new
socket descriptor or an error indication, the protocol address of the client process
(through the cliaddr pointer), and the size of this address (through the addrlen
pointer). If we are not interested in having the protocol address of the client returned,
we set both cliaddr and addrlen to null pointers.

'close' Function
#include <unistd.h>
int close (int sockfd);
Returns: 0 if OK, -1 on error

 

伺服器端:

 

[cpp] view plaincopyprint?
  1. #include<stdio.h>  
  2. #include<sys/socket.h>  
  3. #include<string.h>  
  4. #include<sys/types.h>  
  5. #include<netinet/in.h>  
  6. #include<arpa/inet.h>  
  7. #include<unistd.h>  
  8. #include<stdlib.h>  
  9. #define MAXN 4096   
  10.   
  11. int main(int argc ,char **argv){  
  12.     struct sockaddr_in A ,B ;  
  13.     char meg[MAXN] ;  
  14.     char rev[MAXN] ;  
  15.     socklen_t len;  
  16.     int s_socket,socket_conn;  
  17.     s_socket = socket(AF_INET,SOCK_STREAM,0);     
  18.     if(s_socket < 0){  
  19.         printf("Faile to socket!\n");  
  20.         return 1;  
  21.     }                         
  22.     A.sin_family = AF_INET ;  
  23.     if(argv[1]){  
  24.         A.sin_port = htons(atoi(argv[1])) ;  
  25.     }  
  26.         else  
  27.     A.sin_port = htons(1234);  
  28.     A.sin_addr.s_addr = htonl(INADDR_ANY) ;   
  29.     bind(s_socket ,(struct sockaddr *)&A,sizeof(A));          
  30.     listen(s_socket,5);                               
  31.     printf("Server is Waiting ...\n");            
  32.     len = sizeof(struct sockaddr_in) ;    
  33.     socket_conn = accept(s_socket,(struct sockaddr *)&B ,&len);  
  34.     if(socket_conn >= 0){  
  35.             printf("串連成功,開始通訊!\n");  
  36.             while(1){                                         
  37.                 fgets(meg,MAXN,stdin);  inet_ntoa(B.sin_addr);    
  38.                 len = strlen(meg);  
  39.                 if(meg[len-1] == '\n')  meg[len-1] = 0 ;  
  40.                 send(socket_conn,meg,strlen(meg)+1,0);            
  41.                 printf("已經成功發送%d個位元組\n",len);  
  42.                 if(strcmp(meg,"quit") == 0){  
  43.                     printf("Server is cancelling the communication!\n");  
  44.                     break ;  
  45.                 }  
  46.                 recv(socket_conn,rev,MAXN,0);                         
  47.                 if(strcmp(rev,"quit")==0){  
  48.                     printf("Client is cancelling the communication!\n");  
  49.                     break ;  
  50.                 }  
  51.                 printf("成功接受%d個字元,字元為:%s\n",strlen(rev),rev);  
  52.       
  53.             }  
  54.             close(socket_conn) ;                          
  55.     }  
  56.     else{  
  57.         printf("Faile to aceept!\n");  
  58.     }  
  59.     close(s_socket);                                  
  60.     return 0;  
  61. }  
#include<stdio.h>#include<sys/socket.h>#include<string.h>#include<sys/types.h>#include<netinet/in.h>#include<arpa/inet.h>#include<unistd.h>#include<stdlib.h>#define MAXN 4096 int main(int argc ,char **argv){struct sockaddr_in A ,B ;char meg[MAXN] ;char rev[MAXN] ;socklen_t len;int s_socket,socket_conn;s_socket = socket(AF_INET,SOCK_STREAM,0);if(s_socket < 0){printf("Faile to socket!\n");return 1;}A.sin_family = AF_INET ;if(argv[1]){A.sin_port = htons(atoi(argv[1])) ;}elseA.sin_port = htons(1234);A.sin_addr.s_addr = htonl(INADDR_ANY) ;bind(s_socket ,(struct sockaddr *)&A,sizeof(A));listen(s_socket,5);printf("Server is Waiting ...\n");len = sizeof(struct sockaddr_in) ;socket_conn = accept(s_socket,(struct sockaddr *)&B ,&len);if(socket_conn >= 0){printf("串連成功,開始通訊!\n");while(1){fgets(meg,MAXN,stdin);inet_ntoa(B.sin_addr);len = strlen(meg);if(meg[len-1] == '\n')meg[len-1] = 0 ;send(socket_conn,meg,strlen(meg)+1,0);printf("已經成功發送%d個位元組\n",len);if(strcmp(meg,"quit") == 0){printf("Server is cancelling the communication!\n");break ;}recv(socket_conn,rev,MAXN,0);if(strcmp(rev,"quit")==0){printf("Client is cancelling the communication!\n");break ;}printf("成功接受%d個字元,字元為:%s\n",strlen(rev),rev);}close(socket_conn) ;}else{printf("Faile to aceept!\n");}close(s_socket);return 0;}

 

用戶端:

 

[cpp] view plaincopyprint?
  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<sys/socket.h>  
  4. #include<sys/types.h>  
  5. #include<netinet/in.h>  
  6. #include<arpa/inet.h>  
  7. #include<unistd.h>  
  8. #include<stdlib.h>  
  9. #define MAXN 4096   
  10.   
  11. int main(int argc, char **argv){  
  12.     int c_socket ,conn;  
  13.     int len ;  
  14.     char rev[MAXN] ,buf[MAXN];  
  15.     struct sockaddr_in A ;  
  16.     c_socket = socket(AF_INET,SOCK_STREAM,0);         
  17.     A.sin_family = AF_INET ;      
  18.     if(argv[1]){  
  19.         A.sin_port = htons(atoi(argv[1]));  
  20.     }         
  21.     if(argv[2]){  
  22.         A.sin_addr.s_addr = inet_addr(argv[2]);  
  23.     }  
  24.     conn = connect(c_socket,(struct sockaddr *)&A,sizeof(struct sockaddr_in));        
  25.     if(conn >= 0){  
  26.         printf("進行中通訊!\n");  
  27.         while(1){  
  28.             recv(c_socket,rev,MAXN,0);                                    
  29.             if(strcmp(rev,"quit") == 0){  
  30.                 printf("Server is Cancelling the communication!\n");  
  31.                 break ;  
  32.   
  33.             }  
  34.                         printf("成功接收到了%d字元,字元為:%s\n",strlen(rev),rev);  
  35.             fgets(buf,MAXN,stdin);  
  36.             len = strlen(buf) ;  
  37.             if(buf[len-1] == '\n')  buf[len-1] = 0 ;  
  38.             send(c_socket,buf,strlen(buf)+1,0);           
  39.             if(strcmp(buf,"quit") == 0){  
  40.                 printf("Client is Cancelling the communication!\n");  
  41.                 break ;  
  42.             }  
  43.         }  
  44.         printf("Communication is Done!\n");  
  45.     }  
  46.     else{  
  47.         printf("Faile to connet\n");      
  48.         return 1;  
  49.     }  
  50.     close(c_socket);                      
  51.     return 0;  
  52. }  
#include<stdio.h>#include<string.h>#include<sys/socket.h>#include<sys/types.h>#include<netinet/in.h>#include<arpa/inet.h>#include<unistd.h>#include<stdlib.h>#define MAXN 4096 int main(int argc, char **argv){int c_socket ,conn;int len ;char rev[MAXN] ,buf[MAXN];struct sockaddr_in A ;c_socket = socket(AF_INET,SOCK_STREAM,0);A.sin_family = AF_INET ;if(argv[1]){A.sin_port = htons(atoi(argv[1]));}if(argv[2]){A.sin_addr.s_addr = inet_addr(argv[2]);}conn = connect(c_socket,(struct sockaddr *)&A,sizeof(struct sockaddr_in));if(conn >= 0){printf("進行中通訊!\n");while(1){recv(c_socket,rev,MAXN,0);if(strcmp(rev,"quit") == 0){printf("Server is Cancelling the communication!\n");break ;}                        printf("成功接收到了%d字元,字元為:%s\n",strlen(rev),rev);fgets(buf,MAXN,stdin);len = strlen(buf) ;if(buf[len-1] == '\n')buf[len-1] = 0 ;send(c_socket,buf,strlen(buf)+1,0);if(strcmp(buf,"quit") == 0){printf("Client is Cancelling the communication!\n");break ;}}printf("Communication is Done!\n");}else{printf("Faile to connet\n");return 1;}close(c_socket);return 0;}

GCC編譯過程:

 

gcc -Wal -o Server Server.c

./Server 1234

gcc -Wall -o Client Client.c

./Client  1234 127.0.0.1

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.