通过脚本获取本机IP很容易,当我们写一些逻辑复杂的应用时,就需要考虑类似如下的方式了,下面的方式不一定是最好的,供有需要的博友以参考。
一、编写代码
/*
* create by bdkyr
*date 2015-1-22
*/
#include <stdio.h>
#include <stdlib.h>#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <linux/if.h>
long getlocalhostip(char *dev_name){
int MAXINTERFACES=16;
long ip;
int fd, intrface, retn = 0;
struct ifreq buf[MAXINTERFACES]; ///if.h
struct ifconf ifc; ///if.h
ip = -1;
if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) //socket.h
{
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = (caddr_t) buf;
if (!ioctl (fd, SIOCGIFCONF, (char *) &ifc)) //ioctl.h
{
intrface = ifc.ifc_len / sizeof (struct ifreq);
while (intrface-- > 0)
{
if (ioctl(fd, SIOCGIFFLAGS, (char *) &buf[intrface]))
{
continue;
}
if (buf[intrface].ifr_flags & IFF_LOOPBACK)
continue;
if (!(buf[intrface].ifr_flags & IFF_UP))
continue;
if (ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface]))
{
continue;
}
//char* dev_name="em1";
if (dev_name != NULL && strcmp(dev_name, buf[intrface].ifr_name))
continue;
if (!(ioctl(fd, SIOCGIFADDR, (char *) &buf[intrface])))
{
close(fd);
return ((struct sockaddr_in *) (&buf[intrface].ifr_addr))->sin_addr.s_addr;
}
}
}
close (fd);
}
return 0;
}
union ipu{
long ip;
unsigned char ipchar[4];
};
int main(int argc, char **argv){
union ipu iptest;
iptest.ip = getlocalhostip(argv[1]);
printf("local ip:%x :%3u.%3u.%3u.%3u \n",iptest.ip, iptest.ipchar[0],iptest.ipchar[1],iptest.ipchar[2],iptest.ipchar[3]);
return 0;
}
二、编译
[root@test bdkyr]# gcc get_local_ip.c -o get_local_ip
三、运行
[root@test bdkyr]# ./get_local_ip em1
local ip:c9c8a8c0 :192.168.200.201