当前位置: 技术问答>linux和unix
Linux 下c编程有什么办法获取本机IP?
来源: 互联网 发布时间:2016-01-04
本文导语: rt | char *SearchIP() { int MAXINTERFACES=16; char *ip=NULL; int fd, intrface, retn = 0; struct ifreq buf[MAXINTERFACES]; struct ifconf ifc; if ((fd = socket (AF_INE...
rt
|
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;
}
}
头文件记不清了,与网络有关的都加上吧。
|
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=204211