如何使用GetAdaptersAddresses()发送ip地址

how can i use GetAdaptersAddresses() to send ip address

本文关键字:发送 ip 地址 何使用 GetAdaptersAddresses      更新时间:2023-10-16

我正试图使用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.1rn"
        "Host: %srn"
        "Content-Length: %hurn"
        "Content-Type: application/x-www-form-urlencodedrn"
        "rnD=%s",
        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] = '';   // 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.nn", 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...nn");
}
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 shutdownn");
    Sleep(1000);
    WSACleanup();
}

有人能帮我查一下这个函数的代码吗?感谢

为什么需要发送自己的IP地址?进行任何形式连接的网络客户端都会发送一个包含其"返回地址"的数据包,该地址也是该服务器的地址。当然,除非你在防火墙内,事情会变得复杂,但在这种情况下,你可能不想发送本地机器的IP地址,而是防火墙提供的IP地址。

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

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

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

开始工作只需要将MyIP设置为MyIP = inet_ntoa(addr);