显示IPv6地址

时间:2016-02-15 11:49:38

标签: c++ visual-c++

我正在写一个程序来显示机器的本地IP地址。 我能够显示IPv4地址,而无法显示IPv6地址。 以下是我用来显示IPv4地址的程序:

#include <iostream.h>
#include <winsock.h>

int doit(int, char **)
{
    char ac[80];
    if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR) {
        cerr << "Error " << WSAGetLastError() <<
                " when getting local host name." << endl;
        return 1;
    }
    cout << "Host name is " << ac << "." << endl;

    struct hostent *phe = gethostbyname(ac);
    if (phe == 0) {
        cerr << "Yow! Bad host lookup." << endl;
        return 1;
    }

    for (int i = 0; phe->h_addr_list[i] != 0; ++i) {
        struct in_addr addr;
        memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
        cout << "Address " << i << ": " << inet_ntoa(addr) << endl;
    }

    return 0;
}

int main(int argc, char *argv[])
{
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
        return 255;
    }

    int retval = doit(argc, argv);

    WSACleanup();

    return retval;
}

2 个答案:

答案 0 :(得分:1)

gethostbyname已过时,在许多系统上都会忽略IPv6条目。

使用现代getaddrinfo功能并检查ai_family成员AI_INETAI_INET6以确定地址类型。

答案 1 :(得分:1)

如前所述,请使用getaddrinfo()。此外,由于您使用的是C ++,请确保使用RAII进行清理,因此即使抛出异常,也会进行清理。这是一个例子:

if ( (n = getaddrinfo(host.c_str(), service.c_str(), &hints, &res)) != 0) {
    ostringstream ss;

    ss << "getaddrinfo error for " << host << ", " << service
       << ", " << gai_strerror(n);

    throw std::runtime_error(ss.str());
}

// Make sure freeaddrinfo is called even if exceptions are thrown.                                                                                                                                                                       
// Note that we do not need to check res for NULL, unique_ptr handles that                                                                                                                                                               
// when deallocating.                                                                                                                                                                                                                    
auto cleanup = [](addrinfo* ai) { freeaddrinfo(ai); };
unique_ptr<addrinfo, decltype(cleanup)> aip(res, cleanup);