linux获取网卡的ip,linux编程|获取本地网卡IP地址

linux编程的小实例,可以用来简单练手,熟悉常用函数的用法,获取本地网卡IP地址的源码如下:

/*

× http://www.bdkyr.com

* create by woaimaidong

* 812711277@qq.com

*/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

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@web bdkyr]# gcc get_local_ip.c -o get_local_ip

[root@web bdkyr]# ./get_local_ip eth0

local ip:c9c8a8c0 :192.168.200.201

[root@web bdkyr]# ./get_local_ip eth1

local ip:c90fa8c0 :192.168. 15.201

本文出自《系统开源人》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值