vector<string> get_local_ipaddress()
{
    //本机的IP地址列表(从本地局域网的角度来看)
    vector<string> ips;
 
    char hostname[200];
    if(gethostname(hostname,200) == SOCKET_ERROR)
    {
       return ips;
    }
 
    hostent* hptr = gethostbyname(hostname);
    if (hptr == NULL)
    {
       return ips;
    }
 
    if (hptr->h_addrtype==AF_INET ||
       hptr->h_addrtype==AF_INET6)
    {
       //h_addr_list竟然定义成了char FAR * FAR *,实际上是in_addr**(历史遗留)
       //Null-terminated list of addresses for the host. Addresses are returned in network byte order.
       in_addr **ppaddr=(in_addr **)hptr->h_addr_list;
       for (;*ppaddr!=NULL;ppaddr++)
       {
           char * ip=inet_ntoa(**ppaddr);
           if (ip!=NULL)
           {
              ips.push_back(ip);
           }
       }
    }
 
    return ips;
}

 


本文链接地址: 用gethostbyname获取本机IP地址列表
http://qingfengju.com/index.asp?id=256

分类:Win32/C++ 查看次数:6549 发布时间:2011-9-1 1:14:16