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

相关推荐
炸膛坦客5 分钟前
嵌入式 - 数据结构与算法:(1-4)数据结构 - 单链表的两个核心缺点(引入循环/双向链表)
c语言·数据结构·链表
春蕾夏荷_72829772517 分钟前
2、c++ acl tcp服务器客户端简单实例-服务器端(1)
服务器·c++·tcp/ip
墨染千千秋26 分钟前
C++if判断的使用全解
c++
雪度娃娃26 分钟前
设计模式——单例模式
开发语言·c++·设计模式
嵌入式×边缘AI:打怪升级日志26 分钟前
Tina SDK Linux Kernel 基本使用(实战篇:为7寸RGB LCD触摸屏添加驱动支持).md
linux·运维·服务器
Lenyiin33 分钟前
《LeetCode 顺序刷题》61 - 70
java·c++·python·算法·leetcode·lenyiin
想唱rap43 分钟前
应用层HTTPS协议
服务器·网络·c++·网络协议·http·https
前端之虎陈随易1 小时前
为什么今天还会有新语言?MoonBit 想解决什么问题?
大数据·linux·javascript·人工智能·算法·microsoft·typescript
G.晴天1 小时前
Linux常用命令练习流程
java·linux·运维·服务器·tomcat
_F_y1 小时前
仿RabbitMQ实现消息队列-客户端模块实现
c++·算法·rabbitmq