linux获取本地ip

code

复制代码
#ifdef __linux__
#include <stdio.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <vector>

int32_t get_local_ip(std::vector<std::string>& vIP)
{
    int sockfd;
    struct ifconf ifc;
    char buf[1024] = {0};
    char ipbuf[20] = {0};
    struct ifreq *ifr;

    ifc.ifc_len = 1024;
    ifc.ifc_buf = buf;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        return -1;
    }

    ioctl(sockfd, SIOCGIFCONF, &ifc);
    ifr = (struct ifreq*)buf;

    char ip_buf[20] = {0};
    for (int i = (ifc.ifc_len / sizeof(struct ifreq)); i > 0; i--) 
    {
        (void)inet_ntop(AF_INET, &((struct sockaddr_in*)&ifr->ifr_addr)->sin_addr, ip_buf, 20);

        fprintf(stdout, "ifname:%s,ip:%s\n", ifr->ifr_name, ip_buf);

        vIP.push_back(ip_buf);

        ifr = ifr + 1;
    }

    close(sockfd);

    return 0;
}
int32_t get_local_ip(const char* ifname, std::string& ip) {
    int sockfd;
    struct ifconf ifc;
    char buf[1024] = {0};
    char ipbuf[20] = {0};
    struct ifreq *ifr;

    ifc.ifc_len = 1024;
    ifc.ifc_buf = buf;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        return -1;
    }

    ioctl(sockfd, SIOCGIFCONF, &ifc);
    ifr = (struct ifreq*)buf;

    char ip_buf[20] = {0};
    for (int i = (ifc.ifc_len / sizeof(struct ifreq)); i > 0; i--) 
    {
        (void)inet_ntop(AF_INET, &((struct sockaddr_in*)&ifr->ifr_addr)->sin_addr, ip_buf, 20);

        // fprintf(stdout, "ifname:%s,ip:%s\n", ifr->ifr_name, ip_buf);

        if (strcmp(ifr->ifr_name, ifname) == 0) {
            ip = ip_buf;
            close(sockfd);
            return 0;
        }

        ifr = ifr + 1;
    }

    close(sockfd);

    return -1;
}
void get_local_ip_test(void) {
    std::vector<std::string> vIPs;
    (void)get_local_ip(vIPs);

    std::string res;
    (void)get_local_ip("eth0", res);
    // fprintf(stdout, "res:%s\n", res.c_str());
}

#endif

performance

相关推荐
奔跑吧 android7 分钟前
【linux kernel 常用数据结构和设计模式】【数据结构 2】【通过一个案例属性list、hlist、rbtree、xarray数据结构使用】
linux·数据结构·list·kernel·rbtree·hlist·xarray
汉克老师9 分钟前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(5、机甲战士)
c++·算法·蓝桥杯·01背包·蓝桥杯c++·c++蓝桥杯
Mr_Xuhhh1 小时前
项目需求分析(2)
c++·算法·leetcode·log4j
NiKo_W2 小时前
Linux 文件系统与基础指令
linux·开发语言·指令
PAK向日葵2 小时前
【C/C++】面试官:手写一个memmove,要求性能尽可能高
c语言·c++·面试
Jared_devin2 小时前
二叉树算法题—— [蓝桥杯 2019 省 AB] 完全二叉树的权值
数据结构·c++·算法·职场和发展·蓝桥杯
搞全栈小苏2 小时前
基于Qt QML和C++的MQTT测试客户端(CMakeLists实现)
xml·c++·qt
啊?啊?3 小时前
18 从对象内存到函数调用:C++ 虚函数表原理(继承覆盖 / 动态绑定)+ 多态实战
开发语言·c++·多态原理
bkspiderx3 小时前
C++标准库:文件流类
开发语言·c++
Darkwanderor3 小时前
Linux 的权限详解
linux