MFC获取本机IP地址

来源:互联网 发布:java开发经验总结 编辑:程序博客网 时间:2024/05/22 13:05

获取本机IP地址 

CString sLoginUser;CString sLocalIP;WORD wVersionRequested;WSADATA wsaData;wVersionRequested = MAKEWORD( 2, 0 ); if ( WSAStartup( wVersionRequested, &wsaData ) == 0 ){     sLoginUser.TrimLeft();     sLoginUser.TrimRight();     sLocalIP = CCommonFun::ConvertHostNameToIP(sLoginUser);      WSACleanup( ); }


 

在CCommonFun类中:

CString CCommonFun::ConvertHostNameToIP( const CString &sHostName ){     CString sIP;      HOSTENT *host_entry = gethostbyname(sHostName);     if( host_entry != 0 )     {         sIP.Format("%d.%d.%d.%d",             (host_entry->h_addr_list[0][0]&0x00ff),             (host_entry->h_addr_list[0][1]&0x00ff),             (host_entry->h_addr_list[0][2]&0x00ff),             (host_entry->h_addr_list[0][3]&0x00ff));     }      return sIP;}


 

直接获取:

#include "winsock.h" WORD wVersionRequested;WSADATA wsaData;char name[255];CString ip;PHOSTENT hostinfo;wVersionRequested = MAKEWORD( 2, 0 ); if ( WSAStartup( wVersionRequested, &wsaData ) == 0 ){       if( gethostname ( name, sizeof(name)) == 0)       {             if((hostinfo = gethostbyname(name)) != NULL)             {                   ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);             }       }                    WSACleanup( );}

 

http://www.cppblog.com/wanghaiguang/archive/2012/07/18/184096.html