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

相关推荐
Trouvaille ~22 分钟前
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
c++·c++20·编译原理·编译器·类和对象·rvo·nrvo
little redcap23 分钟前
第十九次CCF计算机软件能力认证-乔乔和牛牛逛超市
数据结构·c++·算法
Dola_Pan26 分钟前
Linux文件IO(二)-文件操作使用详解
java·linux·服务器
机器视觉知识推荐、就业指导1 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
孤寂大仙v1 小时前
【C++】STL----list常见用法
开发语言·c++·list
城南云小白2 小时前
Linux网络服务只iptables防火墙工具
linux·服务器·网络
咩咩大主教2 小时前
C++基于select和epoll的TCP服务器
linux·服务器·c语言·开发语言·c++·tcp/ip·io多路复用
时光飞逝的日子2 小时前
多重指针变量(n重指针变量)实例分析
c语言·指针·多重指针·双重指针·n重指针·指针变量
Flying_Fish_roe2 小时前
linux-网络管理-网络配置
linux·网络·php
FuLLovers2 小时前
2024-09-13 冯诺依曼体系结构 OS管理 进程
linux·开发语言