Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1347828
  • 博文数量: 244
  • 博客积分: 10311
  • 博客等级: 上将
  • 技术积分: 3341
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-14 21:50
文章分类

全部博文(244)

文章存档

2013年(6)

2012年(5)

2011年(16)

2010年(11)

2009年(172)

2008年(34)

分类: LINUX

2011-06-18 10:42:50

/*根据接口名获取IP实例*/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

 

int main(void)

{

        int fd;   

        struct ifreq ifr;

        struct sockaddr_in *sin;

        char LocalIP[32];

        if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1)

        {

                return -1;

        }

        memset(&ifr, 0, sizeof(struct ifreq));

        ifr.ifr_addr.sa_family = AF_INET;

        strcpy(ifr.ifr_name, "eth0");

 

        if (ioctl(fd, SIOCGIFADDR, &ifr) == 0)

        {

                sin = (struct sockaddr_in *) &ifr.ifr_addr;

                strncpy(LocalIP, inet_ntoa(sin->sin_addr),16);

        }

        else

        {

                close(fd);

                return -1;

        }

        printf( "eth0 : %s\n", LocalIP );

        close(fd);

        return 0;

}

 

Makefile:

GetIPByIf : GetIPByIf.o

        gcc GetIPByIf.o -o GetIPByIf

 

GetIPByIf.o : GetIPByIf.c

        gcc -c GetIPByIf.c

 

.PHONY : clean

clean:

        rm *.o GetIPByIf

 

 

 

/*根据接口名获取子网掩码实例*/

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

int main(void)

{

        int fd;   

        struct ifreq ifr;

        struct sockaddr_in *sin;

        char LocalMask[32];

        if((fd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) == -1)

        {

                return -1;

        }

        memset(&ifr, 0, sizeof(struct ifreq));

        ifr.ifr_addr.sa_family = AF_INET;

        strcpy(ifr.ifr_name, "eth0");

 

        if (ioctl(fd, SIOCGIFNETMASK, &ifr) == 0)

        {

                sin = (struct sockaddr_in *) &ifr.ifr_netmask;

                strncpy(LocalMask, inet_ntoa(sin->sin_addr),16);

        }

        else

        {

                close(fd);

                return -1;

        }

        printf( "Mask of eth0 : %s\n", LocalMask );

        close(fd);

        return 0;

}

 

Makefile:

 

GetMaskByIf : GetMaskByIf.o

        gcc GetMaskByIf.o -o GetMaskByIf

GetMaskByIf.o : GetMaskByIf.c

        gcc -c GetMaskByIf.c

.PHONY : clean

clean:

        rm *.o GetMaskByIf

 

阅读(1378) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~