Win32获取主机名和IP地址

来源:互联网 发布:js amr转base64 编辑:程序博客网 时间:2024/05/16 10:01

Win32获取计算机名称和IP地址列表的示例代码。

包括头文件:

#include <Winsock2.h>

lib库:

Ws2_32.lib 

主要实现代码(TCHAR类型):

static BOOL GetHostNameImpl(CString &hostName, CStringArray &ipAddresses) {    TCHAR szHostName[128];    hostName.Empty();    ipAddresses.RemoveAll();    if (gethostname(szHostName, 128) != 0) {        return FALSE;    }    hostName = CString(szHostName);    struct hostent *pHost = NULL;    int i;    pHost = gethostbyname(szHostName);    if (pHost == NULL) return FALSE;    for (i = 0; pHost != NULL && pHost->h_addr_list[i] != NULL; i++) {        LPCTSTR psz = inet_ntoa(*(struct in_addr*)(pHost->h_addr_list[i]));        ipAddresses.Add(CString(psz));    }    return TRUE;}static BOOL GetHostName(CString &hostName, CStringArray &ipAddresses) {    WORD wVersionRequested;    WSADATA wsaData;    wVersionRequested = MAKEWORD( 2, 0 );    WSAStartup( wVersionRequested, &wsaData );    BOOL b = GetHostNameImpl(hostName, ipAddresses) ;    WSACleanup( );    return b;}void Caller() {    CString hostName;    CStringArray ipAddresses;    BOOL b = GetHostName(hostName, ipAddresses) ;}

事实上,以上SDK函数只能使用char*这种数据类型,因此没有必要使用TCHAR,进而为了在Unicode环境中使用,也不需要用CString数据类型。所以直接使用char和std::string这种方式,代码如下:

static BOOL GetHostNameImpl(std::string &hostName, std::list<std::string> &ipAddresses) {    char szHostName[128];    hostName.erase();    ipAddresses.clear();    if (gethostname(szHostName, 128) != 0) {        return FALSE;    }    hostName = std::string(szHostName);    struct hostent *pHost = NULL;    int i;    pHost = gethostbyname(szHostName);    if (pHost == NULL) return FALSE;    for (i = 0; pHost != NULL && pHost->h_addr_list[i] != NULL; i++) {        char* psz = inet_ntoa(*(struct in_addr*)(pHost->h_addr_list[i]));        ipAddresses.push_back(std::string(psz));    }    return TRUE;}static BOOL GetHostName(std::string &hostName, std::list<std::string> &ipAddresses) {    WORD wVersionRequested;    WSADATA wsaData;    wVersionRequested = MAKEWORD( 2, 0 );    WSAStartup( wVersionRequested, &wsaData );    BOOL b = GetHostNameImpl(hostName, ipAddresses) ;    WSACleanup( );    return b;}
0 0
原创粉丝点击