簡體   English   中英

我如何獲得系統的IP地址

[英]How Can I get the Ip address of System

如何獲取系統的IP地址。

我想要在ipconfig/bin/ifconfig之后看到的IP地址

你的意思是'IP地址' - 在Win32中使用GetAdapterAddresses 那里有示例代碼。

這有點令人費解,因為您首先調用API必須查看您需要多少內存,然后使用所需的內存塊再次調用相同的API。 然后,您必須遍歷該內存塊中返回的結構列表,如示例所示。 你最終得到的是這樣的:

SOCKET_ADDRESS結構用於AdapterAddresses參數指向的IP_ADAPTER_ADDRESSES結構。 在針對Windows Vista及更高版本發布的Microsoft Windows軟件開發工具包(SDK)中,頭文件的組織已更改,並且在Ws2def.h頭文件中定義了SOCKET_ADDRESS結構,該文件由Winsock2.h頭文件自動包含。 在針對Windows Server 2003和Windows XP發布的Platform SDK上,SOCKET_ADDRESS結構在Winsock2.h頭文件中聲明。 為了使用IP_ADAPTER_ADDRESSES結構,必須在Iphlpapi.h頭文件之前包含Winsock2.h頭文件。

此時,您可以調用WSAAddressToString來串聯SOCKET_ADDRESS結構中的IP地址,無論是IPv6還是IPv4。

// Requires that WSAStartup has been called
std::vector<std::string> GetIPAddresses(const std::string& hostname)
{
    std::vector<std::string> result;

    // We use getaddrinfo (gethostbyname has been deprecated)
    struct addrinfo hints = {0};
    hints.ai_family = AF_UNSPEC;    // Want both IPv4 and IPv6
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

    struct addrinfo *paddrinfo = NULL;

    if (getaddrinfo(hostname.c_str(), NULL, &hints, &paddrinfo)!=0)
        return result;  // Something is wrong, empty list returned

    // The machine can have multiple IP addresses (IPv4, IPv6, etc.)
    for(struct addrinfo *ptr=paddrinfo; ptr != NULL ;ptr=ptr->ai_next)
    {
        // inet_ntop is not available for all versions of Windows, we implement our own
        char ipaddress[NI_MAXHOST] = {0};
        if (ptr->ai_family == AF_INET)
        {
            if (getnameinfo(ptr->ai_addr, sizeof(struct sockaddr_in), ipaddress, _countof(ipaddress)-1, NULL, 0, NI_NUMERICHOST)==0)
                result.push_back(std::string(ipaddress));
        }
        else if (ptr->ai_family == AF_INET6)
        {
            if (getnameinfo(ptr->ai_addr, sizeof(struct sockaddr_in6), ipaddress, _countof(ipaddress)-1, NULL, 0, NI_NUMERICHOST)==0)
                result.push_back(std::string(ipaddress));
        }
    }

    freeaddrinfo(paddrinfo);

    return result;
}

你的問題不是很具體,但這應該有所幫助:

http://www.codeguru.com/forum/showthread.php?t=233261

如果你是在防火牆后面,想知道你的公網IP地址,你可以使用一個HTTP客戶端庫湊網頁像這樣一個 (有一個剛剛返回的IP地址為text / plain的,但我無法找到它現在)。

如果可以訪問.NET Framework(托管C ++),則可以使用System.Net.Dns.GetHostAddress方法。 有關詳細信息,請參閱此處: http//msdn.microsoft.com/en-us/library/system.net.dns.gethostaddresses.aspx您實際上獲得了一個IP數組,因為一個域名可以對應多個IP。

對於本地IP地址,您可以使用winsock。 看看這個例子

如果使用winsock,請確保在項目中添加適當的庫。 例如,我要在VS 2008中添加Ws2_32.lib

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM