两种获取本机IP地址的方法--发布日期:2008-07-15 23:47

两种方法都是通过先得到主机名再获取IP地址:

The gethostname function retrieves the standard host name for the local computer.

int gethostname(
  char* name,
  int namelen
);
Parameters
name
[out] Pointer to a buffer that receives the local host name.
namelen
[in] Length of the buffer, in bytes    

char hostname[50];

gethostname(hostname,50);即可得到主机名。有了主机名下一步就是获取IP地址,方法一是通过API函数 gethostbyname,需要注意的事这个函数仅仅适用于IPv4,该函数再MSDN中的注释如下:

The gethostbyname function retrieves host information corresponding to a host name from a host database.

Note   The gethostbyname function has been deprecated by the introduction of the getaddrinfo function. Developers creating Windows Sockets 2 applications are urged to use the getaddrinfo function instead of gethostbyname.

struct hostent* FAR gethostbyname(
  const char* name
);

通过传递主机名得到的返回值是一个hosten结构体指针,

typedef struct hostent {
char FAR*
h_name;
char FAR FAR**
h_aliases;
short
h_addrtype;
short
h_length;
char FAR FAR**
h_addr_list; } hostent;
我们需要使用其中的h_addr_list,通过
LPCSTR pszIP=inet_ntoa (*(struct in_addr *)pHost->h_addr_list[0);即可得到IP地址,
注意h_addr_list是主机地址列表,我们这里取的事第一个值,有的电脑装有多个网卡可能有多个IP地址。
方法二是通过API函数getaddrinfo,通过上面的注释也可以看出MS推荐我们使用这个函数代替
gethostbyname,因为这个函数既适用于IPv4也适用于IPv6,详见MSDN。
The getaddrinfo function provides protocol-independent translation from host name to address.
int getaddrinfo(
  const TCHAR* nodename,
  const TCHAR* servname,
  const struct addrinfo* hints,
  struct addrinfo** res
);
 
 
Parameters
 
 
nodename
[in] Pointer to a null-terminated string containing a host (node) name or a numeric host address string. The numeric host address string is a dotted-decimal IPv4 address or an IPv6 hex address.
servname
[in] Pointer to a null-terminated string containing either a service name or port number.
hints
[in] Pointer to an addrinfo structure that provides hints about the type of socket the caller supports. See Remarks.
res
[out] Pointer to a linked list of one or more addrinfo structures containing response information about the host.

MSDN说这个函数是用来提供一种与协议无关的主机名转换为地址的方法,参照MSDN上面的例子经过试验得出下面获取IP的方法:

gethostname(hostname,100);   //获得主机的名称
getaddrinfo(hostname,NULL,&hints,&res);   //利用主机名称获取本地地址
char buff[100];
DWORD bufflen=100;
//将本地地址转换成字符串显示
struct sockaddr_in* pSockaddr=(sockaddr_in*)res->ai_addr;
char *pIP=inet_ntoa(pSockaddr->sin_addr);

这里为什么说经过试验呢,MSDN上面的例子将getaddrinfo函数的前两个参数分别设置为主机IP和端口号,显然第一个参数不能设为主机IP了,根据其注释这个参数既可以为主机名也可以是IP,所以设为主机名,第二个参数说可以是一个服务名或者端口号,如果设为端口号,用WSAAddressToString函数获取的值中就包括该端口号,我也不太清楚这是什么原因,总之感觉这个Socket函数很诡异。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值