获取本机IP地址 2011.12.21
#include <iostream>
using namespace std;
#include <Windows.h>
#pragma comment( lib, "ws2_32.lib" )
char * GetIpList()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
cout<<"WSAStartup failed !"<<endl;
return false;
}
char szhn[256];
int nStatus = gethostname(szhn, sizeof(szhn));
if (nStatus == SOCKET_ERROR )
{
cout<<"gethostname failed, Error code: "<<WSAGetLastError()<<endl;
return false;
}
HOSTENT *host = gethostbyname(szhn);
char * ipaddress =NULL;
if (host != NULL)
{
ipaddress = inet_ntoa( *(IN_ADDR*)host->h_addr_list[0]);
}
WSACleanup();
return ipaddress;
}
int main(int argc, char *argv[])
{
char * ip_address = NULL;
ip_address = GetIpList();
cout<<ip_address<<endl;
return 0;
}
输出:
192.168.1.113
这是我本机的ip地址。
逻辑:先获取本机计算机名,然后通过计算机名获取本机的ip地址。
因为,我本机就一个网卡,所以只获取了一个,假如机子上有多个网卡的话,h_addr_list[i],
根据有几个i,一次获取就行了。
摘自 lingxiu0613的专栏