我如何使用GetAdaptersAddresses()发送IP地址

时间:2013-06-26 11:21:06

标签: c++ visual-studio tcp client-server ip-address

我正在尝试使用TCP在c ++中创建服务器和客户端程序,其中服务器将其IP地址发送到Web主机,然后客户端可以访问Web主机并获取服务器列表。 我试图使用GetAdaptersAddresses()函数发送服务器的IP地址,但我真的不知道该功能是如何工作的。我知道它需要5个参数,但我不知道要为这些参数设置什么值。

这里是所有服务器代码:

    #define WEBSITE         "server.x10host.com"    // Full website URL, withouth HTTP (raises exe size)
#define WEBPAGE         "/Server.php"               // The page of the Server Script (proceed with '\')


#define cAddIP          0       // Send this to the server, to add the IP to the list.
#define cRemIP          1       // Send this to the server, to remove the IP from the list.
#define cGetIPs         2       // Send this to the server, to get the list of all IPs.


SOCKET ListeningSocket;
SOCKADDR_IN ServerAddr;

int Port = 7171;
int MyIP;                       // Hold's the computers external IP (EG on an NAT)

// -------------------------




char* WebPost(char Website[], char Webpage[], char Request[], int RetLen) {
    // Sends an HTTP Post request with POST Data...
    // Absolutly NOT error checking, which needs fixing!

    SOCKET WebSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct hostent *WebHost;
    WebHost = gethostbyname(Website);
    if (WebHost == NULL) {

        if (WSAGetLastError() == WSANOTINITIALISED)
            printf("Error Not Connected!");
        else
            printf("Error: %d", WSAGetLastError());

        Sleep(1000);
        exit(0);

    }
    SOCKADDR_IN SockAddr;
    SockAddr.sin_port   = htons(80);
    SockAddr.sin_family = AF_INET;

    SockAddr.sin_addr.s_addr = *((unsigned long*)WebHost->h_addr);
    connect(WebSocket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr));


    char PostRequest[1024];

    sprintf(PostRequest,
        "POST %s HTTP/1.1\r\n"
        "Host: %s\r\n"
        "Content-Length: %hu\r\n"
        "Content-Type: application/x-www-form-urlencoded\r\n"
        "\r\nD=%s\0",
        Webpage, Website,
        strlen(Request)+2, Request
    );

    send(WebSocket, PostRequest, strlen(PostRequest), 0);


    // Get return data ----------

    char* Data = new char[RetLen];
    recv(WebSocket, Data, 4, 0);

    for (;;) {                          // Skip HTTP headers...

        Data[0] = Data[1];
        Data[1] = Data[2];
        Data[2] = Data[3];

        recv(WebSocket, &Data[3], 1, 0);

        if (Data[0] == '\r' && Data[1] == '\n'
        &&  Data[2] == '\r' && Data[3] == '\n')
            break;

    }

    int DataLen = recv(WebSocket, Data, RetLen, 0);
    Data[DataLen] = '\0';   // Return the data...

    shutdown(WebSocket, 2);
    closesocket(WebSocket);
    return Data;

}



void ServStart() {

    WSADATA wsaData; 

    if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
        printf("Server: WSAStartup failed with error %ld.\n", WSAGetLastError());
        exit(0);
    }

    printf("Server: The Winsock DLL found!\n");
    printf("Server: The current status is %s.\n\n", wsaData.szSystemStatus);

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ) {
        printf("Server: The dll do not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
        WSACleanup();
        exit(0);
    }

    printf("Server: The dll supports the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));


    // Start listening -----------------------------------------------
    ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (ListeningSocket == INVALID_SOCKET) {
        printf("Server: Error at socket, error code: %ld.\n", WSAGetLastError());
        WSACleanup();
        exit(0);
    }

    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(Port);
    ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR) {
        printf("Server: bind failed! Error code: %ld.\n", WSAGetLastError());
        closesocket(ListeningSocket);
        WSACleanup();
        exit(0);
    }

    if (listen(ListeningSocket, 5) == SOCKET_ERROR) {
        printf("Server: listen: Error listening on socket %ld.\n", WSAGetLastError());
        closesocket(ListeningSocket);
        WSACleanup();
        exit(0);
    }

    char SendBuf[32];
    MyIP = GetAdaptersAddresses();      // Get my IP
    sprintf(SendBuf, "%hhu|%s", cAddIP, MyIP);              // Send the server the IP
    WebPost(WEBSITE, WEBPAGE, SendBuf, 0);

    printf("Server: listening for connections...\n\n");

}

void ShutDown() {               // Shut down the server (tells the web server I am offline)

    char SendBuf[32];           // Remove my IP from the list of online servers...
    sprintf(SendBuf, "%hhu|%s", cRemIP, MyIP);
    WebPost(WEBSITE, WEBPAGE, SendBuf, 0);

    printf("Successful shutdown\n");
    Sleep(1000);

    WSACleanup();

}

有人可以帮我解决这个功能的代码吗? 感谢

2 个答案:

答案 0 :(得分:1)

为什么需要发送自己的IP地址?进行任何形式连接的Web客户端将发送包含其“返回地址”的数据包 - 该地址也是该服务器的地址。当然,除非您在防火墙内,事情变得复杂,但在这种情况下,您可能不希望发送本地计算机的IP地址,而是防火墙提供的IP地址。

在服务器上你需要的只是这样的东西:

<?php

echo "Your address is " . $_SERVER['REMOTE_ADDR'] . "<br/>";

?>

(如果您想使用随机机器试用它,可以试试这个:http://linuxhost.matsp.co.uk/calculator/my_ip.php

答案 1 :(得分:0)

让它发挥作用 只需要将MyIP设置为MyIP = inet_ntoa(addr);