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

相关推荐
杜子不疼.17 分钟前
【C++】 map/multimap底层原理与逻辑详解
开发语言·c++
侯小啾43 分钟前
Ubuntu NAT模式设置静态 IP 地址
tcp/ip·ubuntu·php·静态ip
不会kao代码的小王1 小时前
从局域网到全网可用!PDFMathTranslate 翻译工具的进阶使用法
linux
Myosotis5131 小时前
DNS练习
linux·运维·服务器
点云SLAM1 小时前
C++ 中dynamic_cast使用详解和实战示例
开发语言·c++·类型转换·dynamic_cast·c++多态·c++继承
冷徹 .1 小时前
Edu144 CD
c++·算法
wzyannn1 小时前
Linux字符设备驱动开发详细教程(简单字符设备驱动框架)
linux·运维·驱动开发·嵌入式
CodeByV2 小时前
【C++】C++11:右值引用和移动语义
开发语言·c++
LCG元2 小时前
Linux 下的端口转发:ssh、socat、iptables 三种方案对比
linux
LCG元2 小时前
深入理解 Linux 网络命名空间:自己动手实现"虚拟网络"
linux