设为首页 加入收藏

TOP

获取本机IP地址 2011.12.21
2014-11-24 00:12:03 来源: 作者: 【 】 浏览:19
Tags:获取 地址 2011.12.21

#include
using namespace std;

#include


#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 !"<
return false;

}

char szhn[256];

int nStatus = gethostname(szhn, sizeof(szhn));

if (nStatus == SOCKET_ERROR )

{

cout<<"gethostname failed, Error code: "<
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< return 0;

}

输出:

192.168.1.113

这是我本机的ip地址。


逻辑:先获取本机计算机名,然后通过计算机名获取本机的ip地址。

因为,我本机就一个网卡,所以只获取了一个,假如机子上有多个网卡的话,h_addr_list[i],

根据有几个i,一次获取就行了。

摘自 lingxiu0613的专栏

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇几道数值计算题目的c语言实现 下一篇Beej’s Guide Network to Progra..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: