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

相关推荐
Maple_land11 分钟前
Linux进程第八讲——进程状态全景解析(二):从阻塞到消亡的完整生命周期
linux·运维·服务器·c++·centos
嵌入式分享12 分钟前
嵌入式分享#41:RK3576改UART波特率【精简版】
linux·嵌入式硬件·ubuntu·嵌入式
爱吃生蚝的于勒15 分钟前
【Linux】零基础学会Linux之权限
linux·运维·服务器·数据结构·git·算法·github
惜.己22 分钟前
linux中jenkins正常启动外部无法访问
linux·servlet·jenkins
ajassi200025 分钟前
开源 C++ QT QML 开发(十一)通讯--TCP服务器端
c++·qt·开源
lyp90h25 分钟前
高效SQLite操作:基于C++模板元编程的自动化封装
c++
Cyan_RA934 分钟前
Linux 远程Ubuntu服务器本地部署大模型 EmoLLM 中常见的问题及解决方案 万字详解
linux·运维·服务器·ubuntu·大模型·远程部署·emollm
2503_9248068538 分钟前
海外IP的适用业务范围
网络·网络协议·tcp/ip
minji...1 小时前
Linux相关工具vim/gcc/g++/gdb/cgdb的使用详解
linux·运维·服务器·c++·git·自动化·vim
web安全工具库1 小时前
Linux 高手进阶:Vim 核心模式与分屏操作详解
linux·运维·服务器·前端·数据库