• Linux网络编程- ioctl()结合struct ifreq使用案例


    当我们使用 ioctl() 函数和 SIOCGIFFLAGS 请求码来获取网络接口的标志时,我们需要提供一个 struct ifreq 结构体作为参数。这个结构体包含了网络接口的名称和一个将被填充的字段,该字段将在调用返回时包含所请求的标志。

    struct ifreq

    该结构体的定义如下:

    struct ifreq {
        char ifr_name[IFNAMSIZ];   // Interface name
        union {
            struct sockaddr ifr_addr;
            // ... other members ...
            short ifr_flags;  // Flags
            // ... other members ...
        };
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    这只是 struct ifreq 的简化版本,它在 中定义。

    如何使用 ioctl()SIOCGIFFLAGS

    1. 创建一个 struct ifreq 实例。
    2. 设置 ifr_name 字段为我们想查询的接口名称,例如 “eth0”。
    3. 调用 ioctl(),将 SIOCGIFFLAGS 作为请求码和我们的 struct ifreq 实例作为参数。
    4. 当调用返回时,ifr_flags 字段将被填充为该接口的标志。

    示例:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0) {
            perror("socket");
            return 1;
        }
    
        struct ifreq ifr;
        memset(&ifr, 0, sizeof(ifr));
        strncpy(ifr.ifr_name, "enp5s0", IFNAMSIZ - 1); // Assuming 'enp5s0' as the interface
    
        if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0) {
            perror("ioctl");
            close(sockfd);
            return 1;
        }
        
        close(sockfd);
        printf("Flags for 'enp5s0': 0x%x\n", ifr.ifr_flags);
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    majn@tiger:~/C_Project/network_project$ ./ioctl_demo 
    Flags for 'enp5s0': 0x1143
    
    • 1
    • 2

    在上述示例中,我们首先创建了一个用于 ioctl() 调用的临时套接字。然后,我们设置了 ifr_name 为 “enp5s0”,这表示我们想查询这个接口的标志。调用 ioctl() 之后,ifr_flags 将包含 “enp5s0” 接口的标志。

  • 相关阅读:
    仿函数:对优先级队列的优化【C++】
    Prometheus Alertmanager生产配置趟过的坑总结
    【HMS core】【FAQ】【Account Kit】典型问题集2
    基于LSTM和SVM的设备故障诊断(Matlab代码实现)
    torch.nn.init
    网络工程师练习题
    Copliot:让你一秒变身网页达人的神奇助手
    德迅云安全和您聊聊关于DDOS高防ip的一些方面
    用max的角度来解析blender建模!
    5-3Binding对数据的转换和校验
  • 原文地址:https://blog.csdn.net/weixin_43844521/article/details/133350504