Windows和Linux得到本机IP地址的通用函数

王朝system·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

//参数:

ipbuf :存放得到的IP地址列表的数组,实际大小由bufcount指定。

bufcount:想要得到的IP地址列表的个数。

#ifdef _WIN32

#include <winsock2.h>

#include <Ws2tcpip.h>

#pragma comment(lib,"ws2_32.lib")

#else

#include <sys/types.h>

#include <sys/socket.h>

#include <sys/ioctl.h>

#include <net/if.h>

#include <net/if_arp.h>

#include <arpa/inet.h>

#include <unistd.h>

#endif

int getselfiplist(unsigned long ipbuf[],int bufcount)

{

int i,count=0;

#ifdef _WIN32

char hostname[128];

struct hostent* inaddrs;

if(gethostname(hostname,128)==0)

{

inaddrs=gethostbyname(hostname);

if(inaddrs)

{

count=inaddrs->h_length/sizeof(in_addr);

if(count>bufcount)count=bufcount;

for(i=0;i<count;i++)

{

ipbuf[i]=*(unsigned long*)inaddrs->h_addr_list[i];

}

}

}

#else

int sock;

struct sockaddr_in sin;

struct ifreq ifr;

sock = socket(AF_INET, SOCK_DGRAM, 0);

if(sock>=0)//!<0

{

if(bufcount>100)bufcount=100;

for(i=0;i<bufcount;i++)

{

sprintf(ifr.ifr_name,"eth%d",i);

if(ioctl(sock,SIOCGIFADDR,&ifr)<0) break;

::memcpy(&sin, &ifr.ifr_addr, sizeof(sin));

ipbuf[count++]=sin.sin_addr.s_addr;

}

close(sock);

}

#endif

return count;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航