TCP通讯(客户端)

修改自网络:

#include <stdio.h>
#include <string.h>

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

int Client(void);

unsigned short port;

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));
    port = rand();
    return Client();
}

int Client(void)
{
    WSADATA wsaData;
    SOCKET iSockCliID;
    struct sockaddr_in stCliAddr, stServAddr;
    char buff[1024] = "Hello Word!";

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
    {
        printf("Error at WSAStartup().\n");
        return 255;
    }

    if ((iSockCliID = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Server: Can not open a stream socket!\n");
        return 1;
    }
    stCliAddr.sin_family = AF_INET;
    stCliAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    stCliAddr.sin_port = htons(port);
    if ((bind(iSockCliID, (struct sockaddr *)&stCliAddr, sizeof (struct sockaddr_in))) < 0)
    {
        printf("Client: Con not bind address!\n");
        return 2;
    }
    stServAddr.sin_family = AF_INET;
    stServAddr.sin_addr.S_un.S_addr = inet_addr("192.168.7.104");
    stServAddr.sin_port = htons(8001);
    if (connect(iSockCliID, (struct sockaddr *)&stServAddr, sizeof (struct sockaddr_in)) < 0)
    {
        printf("Client: Can not connect to the sercer!\n");
        return 3;
    }

    send(iSockCliID, buff, strlen(buff), 0);
    memset(buff, 0, sizeof (buff));
    recv(iSockCliID, buff, sizeof (buff), 0);
    printf("%s\n", buff);
    closesocket(iSockCliID);
    system("pause");
    return 0;
}


你可能感兴趣的:(TCP通讯(客户端))