获取本机IP地址
1 CString sLoginUser;
2 CString sLocalIP;
3 WORD wVersionRequested;
4 WSADATA wsaData;
5 wVersionRequested = MAKEWORD( 2, 0 );
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( 2, 0 );
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
王海光 阅读(4309)
评论(0) 编辑 收藏 引用 所属分类:
MFC