VC++ 網絡編程總結(二)

二、基本的Windows Socket API編程

  • 須要在程序中添加下面的包含語句:#include <winsock2.h>   #pragma comment( lib, "WS2_32" )
  • 使用Vc++編譯時需添加編譯連接依賴項ws2_32.lib庫
  • 協議尋址

     在winsock中,應用程序經過Sockaddr_in 結構來指定IP地址和服務端口信息:c++

      sockaddr_in internetAddr;編程

      int nPortID = 5320;服務器

      internetAddr.sin_family = AF_INET;socket

      internetAddr.sin_addr.s_addr = inet_addr(「202.202.42.88」);函數

      internetAddr.sin_port = htons(nPortID);spa

    ip地址不容易記憶,還提供了許多地址和名稱解析函數如gethostbyname,gethostbyaddr等3d

2.1經常使用函數

                                 2013-08-19_182929

2.2 TCP實例應用

=======客戶端======code

#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib,"WS2_32")

int main(int argc, char* argv[])
{
    SOCKET sock;
    struct sockaddr_in sa;
    int err;
    int servport = 5555;
    char buff[256];

    int len;
    WSADATA ws;

    //初始化WinSock
    if(WSAStartup(0x0101,&ws) != 0)
    {
        printf("WSAStartup() failed!\n");
        exit(-1);
    }

    //建立套接字
    sock =socket(AF_INET,SOCK_STREAM,0);
    //定義服務器地址結構
    memset(&sa,0,sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_port = htons(servport);
    sa.sin_addr.s_addr=inet_addr("127.0.0.1") ;

    //連接服務器
    err=connect(sock,(const sockaddr*)&sa,sizeof(sa));

    //接收歡迎詞
    memset(buff,0,sizeof(buff));
    len =recv(sock,buff,sizeof(buff),0);
    printf("%s\n",buff);
    closesocket(sock);
    WSACleanup();
    return 0;
}

 

=======服務器=======blog

 

#include <stdio.h>
#include <winsock2.h>
#pragma comment (lib,"WS2_32")

int main(int argc, char* argv[])
{
    SOCKET servsock,clisock;
    struct sockaddr_in sa;
    struct sockaddr_in cliaddr;
    int servport = 5555;
    char buff[256];
    WSADATA ws;
    int len,err;

    //初始化Winsock
    if(WSAStartup(0X0101,&ws) != 0)
    {
        printf("WSAStartup() failed!\n");
        exit(-1);
    }
    //建立套接字
    printf("Create Socket...\n");
    servsock = socket(AF_INET,SOCK_STREAM,0);

    //填充服務器地址結構
    memset(&sa,0,sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_port=htons(servport);
    sa.sin_addr.s_addr = inet_addr("127.0.0.1");

    //綁定套接字到服務器地址結構
    printf("Binding...\n");
    err = bind(servsock,(const sockaddr*)&sa,sizeof(sa));
    
    if(err != 0)
    {
        fprintf(stderr,"Bind failed:%d\n",WSAGetLastError());
        exit(-2);
    }

    //監聽套接字
    printf("Listeing...\n");
    err = listen(servsock,5);
    if(err != 0)
    {
        fprintf(stderr,"Listen failed:%d\n",WSAGetLastError());
        exit(-3);
    }

    //等待鏈接請求
    printf("Waiting Request...\n");
    len = sizeof(cliaddr);
    clisock =accept(servsock,(struct sockaddr*)&cliaddr,&len);
    printf("Accept Client:%s:%d",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port));
    
    sprintf(buff,"Welcome %s",inet_ntoa(cliaddr.sin_addr));
    send(clisock,buff,strlen(buff),0);
    closesocket(clisock);
    WSACleanup();

    return 0;
}
相關文章
相關標籤/搜索