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
本文出自《系统开源人》