文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>linux下获取本机IP地址的方法

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

时间:2010-06-30  来源:rain_fish

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++;
    }
}


相关阅读 更多 +
排行榜 更多 +
战机公司汉化版下载

战机公司汉化版下载

飞行射击 下载
<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" alt="机器人狙击手最新版" />

<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748214895997494.png" alt="机器人狙击手最新版" />

飞行射击 下载
<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" alt="我的枪有子弹最新版" />

<img preview="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" width="32" height="32" src="http://pic.pdowncc.com/uploadimg/ico/2025/0526/1748213241693464.png" alt="我的枪有子弹最新版" />

飞行射击 下载