『转』windows和linux进行socket通信

【 声明:版权所有,欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】

    在公司里面,我们平时使用的机器一般都是windows系统,但是开发、编译的机器往往是linux服务器。通过ping、ftp、samba、telnet、ssh,人们可以很方便与服务器连接。windows系统使用的是windows socket,而linux使用的posix socket,那么这两个socket之间是怎么通信的呢?网上关于windows与windows通信的代码很多,linux与linux通信的代码也很多,但是windows和linux通信的代码很少。这里,我就想写一个简单的socket代码,实现linux和windows的通信。

    其实,广义一点看,网页访问、邮箱、游戏、聊天工具都是利用socket实现的,当然后面实现的逻辑要比我们写的代码复杂的多。但是,我们完全可以利用简单的代码来说明socket通信问题,能做到这一点就足够了。这也是我一直推崇的方法,用最简单的代码表达最实际的功能。

    windows侧的client代码,

[cpp] view plain copy print ?

  1. #include <stdio.h> 

  2. #include <Windows.h> 

  3.   

  4. #pragma comment(lib,"ws2_32.lib") 

  5. #define  PORT 4000 

  6. #define  IP_ADDRESS "192.168.1.102" 

  7.   

  8. int main(int argc,char* argv[]) 

  9.     WSADATA  Ws; 

  10.     SOCKET ClientSocket; 

  11.     struct sockaddr_in ClientAddr; 

  12.     int Ret = 0; 

  13.     char SendBuffer[MAX_PATH]; 

  14.  

  15.     /* Init Windows Socket */ 

  16.     if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 ) 

  17.     { 

  18.         printf("Init Windows Socket Failed::%d\n", GetLastError()); 

  19.         return -1; 

  20.     } 

  21.   

  22.     /* Create Socket */ 

  23.     ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 

  24.     if ( ClientSocket == INVALID_SOCKET ) 

  25.     { 

  26.         printf("Create Socket Failed::%d\n", GetLastError()); 

  27.         return -1; 

  28.     } 

  29.  

  30.     ClientAddr.sin_family = AF_INET; 

  31.     ClientAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); 

  32.     ClientAddr.sin_port = htons(PORT); 

  33.     memset(ClientAddr.sin_zero, 0x00, 8); 

  34.  

  35.     /* connect socket */ 

  36.     Ret = connect(ClientSocket,(struct sockaddr*)&ClientAddr,sizeof(ClientAddr)); 

  37.     if ( Ret == SOCKET_ERROR ) 

  38.     { 

  39.         printf("Connect Error::%d\n", GetLastError()); 

  40.         return -1; 

  41.     } 

  42.     else 

  43.     { 

  44.         printf("Connect succedded!\n"); 

  45.     } 

  46.  

  47.     while (1) 

  48.     { 

  49.         scanf("%s", SendBuffer); 

  50.  

  51.         /* send data to server */ 

  52.         Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0); 

  53.         if ( Ret == SOCKET_ERROR ) 

  54.         { 

  55.             printf("Send Info Error::%d\n", GetLastError()); 

  56.             break; 

  57.         } 

  58.          

  59.         if('q' == SendBuffer[0]) 

  60.         { 

  61.             break; 

  62.         } 

  63.     } 

  64.      

  65.     /* close socket */ 

  66.     closesocket(ClientSocket); 

  67.     WSACleanup(); 

  68.   

  69.     return 0; 

  70.   

    #include <stdio.h>
    #include <Windows.h>

    #pragma comment(lib,"ws2_32.lib")
    #define PORT 4000
    #define IP_ADDRESS "192.168.1.102"

    int main(int argc, char* argv[])
    {
    WSADATA Ws;
    SOCKET ClientSocket;
    struct sockaddr_in ClientAddr;
    int Ret = 0;
    char SendBuffer[MAX_PATH];

    /* Init Windows Socket */
    if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 )
    {
        printf("Init Windows Socket Failed::%d\n", GetLastError());
        return -1;
    }
    
    /* Create Socket */
    ClientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if ( ClientSocket == INVALID_SOCKET )
    {
        printf("Create Socket Failed::%d\n", GetLastError());
        return -1;
    }
    
    ClientAddr.sin_family = AF_INET;
    ClientAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS);
    ClientAddr.sin_port = htons(PORT);
    memset(ClientAddr.sin_zero, 0x00, 8);
    
    /* connect socket */
    Ret = connect(ClientSocket,(struct sockaddr*)&ClientAddr, sizeof(ClientAddr));
    if ( Ret == SOCKET_ERROR )
    {
        printf("Connect Error::%d\n", GetLastError());
        return -1;
    }
    else
    {
        printf("Connect succedded!\n");
    }
    
    while (1)
    {
        scanf("%s", SendBuffer);
    
    	/* send data to server */
        Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0);
        if ( Ret == SOCKET_ERROR )
        {
            printf("Send Info Error::%d\n", GetLastError());
            break;
        }
    	
    	if('q' == SendBuffer[0])
    	{
    		break;
    	}
    }
    
    /* close socket */
    closesocket(ClientSocket);
    WSACleanup();
    
    return 0;
    

    }

    linux侧的server代码,

[cpp] view plain copy print ?

  1. #include <netinet/in.h>     

  2. #include <sys/types.h>     

  3. #include <sys/socket.h>     

  4. #include <stdio.h>         

  5. #include <stdlib.h>        

  6. #include <string.h>        

  7.  

  8. #define HELLO_WORLD_SERVER_PORT    4000 

  9. #define LENGTH_OF_LISTEN_QUEUE 20 

  10. #define BUFFER_SIZE 1024 

  11.  

  12. int main(int argc,char **argv) 

  13.     struct sockaddr_in server_addr; 

  14.     int server_socket; 

  15.     int opt = 1; 

  16.     

  17.     bzero(&server_addr,sizeof(server_addr));  

  18.      

  19.     server_addr.sin_family = AF_INET; 

  20.     server_addr.sin_addr.s_addr = htons(INADDR_ANY); 

  21.     server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT); 

  22.  

  23.     /* create a socket */ 

  24.     server_socket = socket(PF_INET,SOCK_STREAM,0); 

  25.     if( server_socket < 0) 

  26.     { 

  27.         printf("Create Socket Failed!"); 

  28.         exit(1); 

  29.     } 

  30.   

  31.     /* bind socket to a specified address*/ 

  32.     setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt,sizeof(opt)); 

  33.     if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))) 

  34.     { 

  35.         printf("Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT);  

  36.         exit(1); 

  37.     } 

  38.  

  39.     /* listen a socket */ 

  40.     if(listen(server_socket, LENGTH_OF_LISTEN_QUEUE)) 

  41.     { 

  42.         printf("Server Listen Failed!");  

  43.         exit(1); 

  44.     } 

  45.      

  46.     /* run server */ 

  47.     while (1)  

  48.     { 

  49.         struct sockaddr_in client_addr; 

  50.         int client_socket;       

  51.         socklen_t length; 

  52.         char buffer[BUFFER_SIZE]; 

  53.  

  54.         /* accept socket from client */ 

  55.         length = sizeof(client_addr); 

  56.         client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length); 

  57.         if( client_socket < 0) 

  58.         { 

  59.             printf("Server Accept Failed!\n"); 

  60.             break; 

  61.         } 

  62.          

  63.         /* receive data from client */ 

  64.         while(1) 

  65.         { 

  66.             bzero(buffer, BUFFER_SIZE); 

  67.             length = recv(client_socket, buffer, BUFFER_SIZE, 0); 

  68.             if (length < 0) 

  69.             { 

  70.                 printf("Server Recieve Data Failed!\n"); 

  71.                 break; 

  72.             } 

  73.              

  74.             if('q' == buffer[0]) 

  75.             { 

  76.                 printf("Quit from client!\n"); 

  77.                 break; 

  78.             } 

  79.              

  80.             printf("%s\n", buffer); 

  81.         }    

  82.          

  83.         close(client_socket); 

  84.     } 

  85.      

  86.     close(server_socket); 

  87.     return 0; 

  88. #include <netinet/in.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    #define HELLO_WORLD_SERVER_PORT 4000
    #define LENGTH_OF_LISTEN_QUEUE 20
    #define BUFFER_SIZE 1024

    int main(int argc, char **argv)
    {
    struct sockaddr_in server_addr;
    int server_socket;
    int opt = 1;

    bzero(&server_addr,sizeof(server_addr)); 
    
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htons(INADDR_ANY);
    server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);
    
    /* create a socket */
    server_socket = socket(PF_INET,SOCK_STREAM,0);
    if( server_socket < 0)
    {
        printf("Create Socket Failed!");
        exit(1);
    }
    
    /* bind socket to a specified address*/
    setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr)))
    {
        printf("Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT); 
        exit(1);
    }
    
    /* listen a socket */
    if(listen(server_socket, LENGTH_OF_LISTEN_QUEUE))
    {
        printf("Server Listen Failed!"); 
        exit(1);
    }
    
    /* run server */
    while (1) 
    {
        struct sockaddr_in client_addr;
    	int client_socket;		
        socklen_t length;
    	char buffer[BUFFER_SIZE];
    
    	/* accept socket from client */
    	length = sizeof(client_addr);
        client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);
        if( client_socket < 0)
        {
            printf("Server Accept Failed!\n");
            break;
        }
        
    	/* receive data from client */
    	while(1)
    	{
    		bzero(buffer, BUFFER_SIZE);
    		length = recv(client_socket, buffer, BUFFER_SIZE, 0);
    		if (length < 0)
    		{
    			printf("Server Recieve Data Failed!\n");
    			break;
    		}
    		
    		if('q' == buffer[0])
    		{
    			printf("Quit from client!\n");
    			break;
    		}
    		
    		printf("%s\n", buffer);
    	}	
    	
        close(client_socket);
    }
    
    close(server_socket);
    return 0;
    

    }

    windows侧的代码使用vc6.0编译就可以,而linux侧的代码用gcc就ok了,即gcc server.c -o server。首先,在linux侧输入./server,然后打开widnows侧的client程序,然后在windows侧的每一个字符输入都会在linux打印出来。如果想退出,输入q即可。但是此时server不会退出,它在等待下一个client的通信,继续服务于大家,就是这么简单。

    这里的server和client代码是根据网友的代码修改而来,一并表示感谢。如有侵权,请邮件告知。

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/8574809

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();