面对现实,超越自己
逆水行舟,不进则退
posts - 269,comments - 32,trackbacks - 0
获取本机IP地址 
 1 CString sLoginUser;
 2 CString sLocalIP;
 3 WORD wVersionRequested;
 4 WSADATA wsaData;
 5 wVersionRequested = MAKEWORD( 20 );
 6 
 7 if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
 8 {
 9     sLoginUser.TrimLeft();
10     sLoginUser.TrimRight();
11     sLocalIP = CCommonFun::ConvertHostNameToIP(sLoginUser);
12 
13     WSACleanup( );
14 }

在CCommonFun类中:
 1 CString CCommonFun::ConvertHostNameToIP( const CString &sHostName )
 2 {
 3     CString sIP;
 4 
 5     HOSTENT *host_entry = gethostbyname(sHostName);
 6     if( host_entry != 0 )
 7     {
 8         sIP.Format("%d.%d.%d.%d",
 9             (host_entry->h_addr_list[0][0]&0x00ff),
10             (host_entry->h_addr_list[0][1]&0x00ff),
11             (host_entry->h_addr_list[0][2]&0x00ff),
12             (host_entry->h_addr_list[0][3]&0x00ff));
13     }
14 
15     return sIP;
16 }

直接获取:
 1 #include "winsock.h"
 2 
 3 WORD wVersionRequested;
 4 WSADATA wsaData;
 5 char name[255];
 6 CString ip;
 7 PHOSTENT hostinfo;
 8 wVersionRequested = MAKEWORD( 20 );
 9 
10 if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
11 {
12       if( gethostname ( name, sizeof(name)) == 0)
13       {
14             if((hostinfo = gethostbyname(name)) != NULL)
15             {
16                   ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
17             }
18       }
19             
20      WSACleanup( );
21 }



posted on 2012-07-18 18:13 王海光 阅读(4268) 评论(0)  编辑 收藏 引用 所属分类: MFC

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理