0

我需要一些帮助

上周,我按照教程使用 winsock2 用 C++ 编写了我的第一个服务器应用程序。本教程不连接到特定 IP,但使用名为“SocketTest”的工具,我可以通过 IP 127.0.0.1 和端口 21 连接到服务器。

我想使用特定的 IP 地址 (192.168.1.10) 和端口 (17013)。我知道如何做端口,但我儿子不知道如何连接到特定的 IP 地址。谁能帮助我并向我解释一下?这是我使用的代码:

#include <iostream>
#include <WS2tcpip.h>

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

using namespace std;

void main()
{

    //initialize winsock (sockets)
    WSADATA wsData;
    WORD ver = MAKEWORD(2, 2);

    int wsOk = WSAStartup(ver, &wsData);
    if (wsOk != 0)
    {
        cerr << "Can't initialize winsock! quitting" << endl;
        return;
    }

    //create a socket
    SOCKET listening = socket(AF_INET, SOCK_STREAM, 0);
    if (listening == INVALID_SOCKET)
    {
        cerr << "Can't create a socket! quitting" << endl;
        return;
    }

    //bind the ip to a socket address and port
    sockaddr_in hint;
    hint.sin_family = AF_INET;
    hint.sin_port = htons(21);
    hint.sin_addr.S_un.S_addr = INADDR_ANY; //could also use inet_pton

    bind(listening, (sockaddr*)&hint, sizeof(hint));

    //tell winsock the socket is for listening
    listen(listening, SOMAXCONN);

    //wait for a connection
    sockaddr_in client;
    int clientSize = sizeof(client);

    SOCKET clientSocket = accept(listening, (sockaddr*)&client, &clientSize);
    if (clientSocket == INVALID_SOCKET)
    {
        cerr << "Can't make connection! quitting" << endl;
        return;
    }

    char host[NI_MAXHOST];      //client's remote name
    char service[NI_MAXSERV];   //service (i.e. port) the client is connect on

    ZeroMemory(host, NI_MAXHOST);
    ZeroMemory(service, NI_MAXSERV);

    if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0)
    {
        cout << host << " connected on port " << service << endl;
    }
    else
    {
        inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST);
        cout << host << " connected on port " <<
            ntohs(client.sin_port) << endl;
    }

    //close listening socket
    closesocket(listening);

    char buf[4096];

    while (true) //this part of the code will be used to send and receive data
    {
        ZeroMemory(buf, 4096);
        float X = 12.4;
        float Y = 456;
        float Z = 900.87;

        sprintf_s(buf, "(%lf,%lf,%lf)",X,Y,Z);
        size_t buf_len = strlen(buf);

        send(clientSocket, buf, buf_len, 0);




        int bytesReceived = recv(clientSocket, buf, 4096, 0);
    }

    //close the socket(s)
    closesocket(clientSocket);

    //shutdown/cleanup winsock (sockets)
    WSACleanup();

}
4

0 回答 0