#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的專欄