红联Linux门户
Linux帮助

Get IP address under Linux

发布时间:2007-11-21 10:32:30来源:红联作者:together
we can get device IP address by domain name.Firstly get the domain name by gethostname(char *,int) function,and then using the following function we get a data structure including the ip address: hostent * gethostbyname(char *).eg.

int GetIP()
{
int white_sock;
struct hostent *site;
char hostName[20];

memset(hostName,0,sizeof(hostName));
gethostname(hostName,sizeof(hostName));

printf("host name: %s\n",hostName);

site=gethostbyname(hostName); //根据域名信息获得主机的IP地址
if(site == NULL)
{
printf("Get site error!\n");
return -1;
}

printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)site->h_addr)));
return 1;
}

However,the ip address got in the way above is always not the one we really want.So we can use another method as following:

int GetDeviceIpAddress(char *ipAddr)
{
register int fd, intrface;
struct ifreq buf[MAXINTERFACES];
struct ifconf ifc;

if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0)
{
goto Exit;
}

ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t) buf;
if (ioctl (fd, SIOCGIFCONF, (char *) &ifc) < 0)
{
goto Exit;
}

intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-- > 0)
{
if ((ioctl (fd, SIOCGIFFLAGS, (char *) &buf[intrface])) < 0)
{
continue;
}

if (!(ioctl (fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
sprintf(ipAddr,"%s",inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
if( strcmp(ipAddr,"127.0.0.1") != 0 )
{
close(fd);
return 1;
}
}
else
{
goto Exit;
}

}

Exit:
close (fd);
return -1;
}

Actually,this way can get all devices' ip address,no matter how many net cards you have.so it is great.
文章评论

共有 0 条评论