Chinaunix首页 | 论坛 | 博客
  • 博客访问: 235973
  • 博文数量: 48
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 480
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-24 11:02
文章分类

全部博文(48)

文章存档

2010年(33)

2009年(14)

2008年(1)

我的朋友

分类: LINUX

2010-07-05 16:16:17

获取eth*接口的IP地址

#include
#include
#include
#include
#include
#include
#include
#include
#include

#define MAXINTERFACES 16
#define MAC_ADDR_LEN 18
#define ADDR_LEN 16

#define ETH_INTERFACE_NAME "eth"

void err_quit(char *msg);
void getIP(char *addr);

int main(int argc, char *argv[])
{
        char addr[ADDR_LEN] = {0,};

        getIP(addr);

        printf("%s\n", addr);

        return 0;
}

void err_quit(char *msg)
{
        perror(msg);
        exit(1);
}

void getIP(char *addr)
{
        int sock_fd;
        struct ifreq buf[MAXINTERFACES];
        struct ifconf ifc;
        int inter_num;
        char *temp = NULL;

        if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
                err_quit("Create socket failed");

        ifc.ifc_len = sizeof(buf);
        ifc.ifc_req = buf;

        if(ioctl(sock_fd, SIOCGIFCONF, (char *)&ifc) < 0)
                err_quit("Get a list of interface addresses failed");

        inter_num = ifc.ifc_len / sizeof(struct ifreq);
        printf("The number of interfaces is %d\n", inter_num);

        while(inter_num--) {
                if(strstr(buf[inter_num].ifr_name, ETH_INTERFACE_NAME) == NULL)
                        continue;

                if(ioctl(sock_fd, SIOCGIFADDR, (char *)&buf[inter_num]) < 0)
                        err_quit("Get interface address failed");

                temp = inet_ntoa(((struct sockaddr_in*)(&buf[inter_num].ifr_addr))->sin_addr);
                strncpy(addr, temp, ADDR_LEN);
                printf("IP address is %s\n", addr);
        }
}

阅读(1966) | 评论(0) | 转发(0) |
0

上一篇:查看Linux版本信息

下一篇:LiveValidation验证

给主人留下些什么吧!~~