当前位置: 技术问答>linux和unix
如何获得本机的ip地址
来源: 互联网 发布时间:2015-10-07
本文导语: 请问如何在linux7.3下面获得本机的ip地址。谢谢 | char *SearchIP() { int MAXINTERFACES=16; char *ip=NULL; int fd, intrface, retn = 0; struct ifreq buf[MAXINTERFACES]; struct i...
请问如何在linux7.3下面获得本机的ip地址。谢谢
|
char *SearchIP()
{
int MAXINTERFACES=16;
char *ip=NULL;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0)
{
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc))
{
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-->0)
{
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
break;
}
}
}
close (fd);
return ip;
}
}
头文件记不清了,与网络有关的都加上吧。
{
int MAXINTERFACES=16;
char *ip=NULL;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;
if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0)
{
ifc.ifc_len = sizeof buf;
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc))
{
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-->0)
{
if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
ip=(inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
break;
}
}
}
close (fd);
return ip;
}
}
头文件记不清了,与网络有关的都加上吧。
|
先调用gethostname,然后调用gethostbyname,本地的IP就在gethostbyname得到的那个struct sockaddr里面