Chinaunix首页 | 论坛 | 博客
  • 博客访问: 349158
  • 博文数量: 46
  • 博客积分: 4936
  • 博客等级: 上校
  • 技术积分: 575
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-25 20:14
文章分类

全部博文(46)

文章存档

2012年(4)

2011年(1)

2010年(23)

2009年(18)

分类: LINUX

2010-06-30 11:45:53

linux下获取本机IP地址的方法
 

#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <iostream>
using namespace std;
//from http://rainfish.cublog.cn/
//by ben
int main()
{
    int sock;
    struct ifconf conf;
    struct ifreq *ifr;
    char buff[BUFSIZ];
    int num;
    int i;
    int ret = 0;

    sock = socket(PF_INET, SOCK_DGRAM, 0);
    conf.ifc_len = BUFSIZ;
    conf.ifc_buf = buff;
/*
SIOCGIFCONF
返 回系统中配置的所有接口的配置信息。
*/
    ioctl(sock, SIOCGIFCONF, &conf);
    num = conf.ifc_len / sizeof(struct ifreq);
    ifr = conf.ifc_req;
    cout << "ip's num " << num << endl;

    string str_ip;
    for (i = 0; i < num; i++)
    {
        struct sockaddr_in *sin = (struct sockaddr_in *) (&ifr->ifr_addr);
        // SIOCGIFFLAGS 可以获取接口标志。
        ioctl(sock, SIOCGIFFLAGS, ifr);
       
        //cout << "ifr->ifr_flags: " << ifr->ifr_flags << endl;

        if (((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP))
        {
            str_ip = inet_ntoa(sin->sin_addr);
            cout << "ip is " << str_ip << endl;
        }
        ifr++;
    }
}


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