LINUX下C语言读取网卡IP

在Linux系统下,C语言可以通过读取系统文件来获取网卡的IP地址。

1、代码案例

c 复制代码
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <unistd.h>
    
    int get_ip_address(const char *ifname, char *ip_str, size_t size) {
        struct sockaddr_in sa;
        int fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (fd < 0) {
            perror("socket");
            return -1;
        }
    
        memset(&sa, 0, sizeof(sa));
        sa.sin_family = AF_INET;
        sa.sin_addr.s_addr = INADDR_ANY;
    
        if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
            perror("bind");
            close(fd);
            return -1;
        }
    
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0) {
            perror("setsockopt");
            close(fd);
            return -1;
        }
    
        if (getsockname(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
            perror("getsockname");
            close(fd);
            return -1;
        }
    
        close(fd);
    
        if (sa.sin_family != AF_INET) {
            fprintf(stderr, "Unsupported address family\\n");
            return -1;
        }
    
        inet_ntop(AF_INET, &(sa.sin_addr), ip_str, size);
        return 0;
    }
    
    int main() {
        char ip[INET_ADDRSTRLEN];
        if (get_ip_address("eth0", ip, sizeof(ip)) < 0) {
            fprintf(stderr, "Failed to get IP address\\n");
            return EXIT_FAILURE;
        }
    
        printf("IP Address: %s\\n", ip);
        return EXIT_SUCCESS;
    }

这个程序首先创建了一个UDP套接字,并绑定到任何可用的IP地址和端口上。然后,它使用getsockname函数获取套接字的本地地址,这个地址就是当前使用的IP地址。最后,程序使用inet_ntop函数将IP地址从二进制格式转换为可读的字符串格式。

请注意,这个程序假设eth0是您想要获取IP地址的网卡名称。在不同的Linux系统中,网卡的名称可能不同(例如,可能是eth1enp0s3等)。此外,某些系统可能需要root权限来执行此操作。

编译并运行此程序:

bash 复制代码
    gcc -o get_ip get_ip.c
    sudo ./get_ip

这将输出eth0网卡的IP地址。

相关推荐
一个平凡而乐于分享的小比特5 分钟前
Linux内核构建三剑客:Kconfig、.config与Makefile关系详解
linux·makefile·kconfig·.config
Dillon Dong7 分钟前
服务器运维:Linux 磁盘查看 & 清理常用命令
linux·运维·服务器
ben9518chen12 分钟前
Linux用户管理
linux·运维·服务器
用户6135411460161 小时前
xampplinux_v174beta11在 Linux 下的安装与配置步骤
linux
Byron Loong1 小时前
【系统】Mac系统和Linux 指令对比
linux·macos·策略模式
清水白石0081 小时前
深入 Python 的底层世界:从 C 扩展到 ctypes 与 Cython 的本质差异全解析
c语言·python·neo4j
markvivv1 小时前
在 Kylin Linux Advanced Server for Kunpeng V10 上构建 VSCode 1.106
linux·vscode·kylin
看见繁华2 小时前
Linux 交叉编译实践笔记
linux·运维·笔记
进击中的小龙2 小时前
基于rtklib的载波相位平滑伪距
c语言·算法·数学建模·gitee
tianyuanwo2 小时前
深入解析CentOS 8网络配置:NetworkManager DNS管理机制与网卡类型深度剖析
linux·网络·centos