简体   繁体   English

Linux 以编程方式向上/向下接口 kernel

[英]Linux programmatically up/down an interface kernel

What is the programmatic way of enabling or disabling an interface in kernel space?在 kernel 空间中启用或禁用接口的编程方式是什么? What should be done?应该做什么?

...by using IOCTL's... ...通过使用 IOCTL 的...

ioctl(skfd, SIOCSIFFLAGS, &ifr);

... with the IFF_UP bit set or unset depending on whether you want bring the interface up or down accordingly, ie: ...设置或取消设置 IFF_UP 位取决于您是否要相应地启动或关闭接口,即:

static int set_if_up(char *ifname, short flags)
{
    return set_if_flags(ifname, flags | IFF_UP);
}

static int set_if_down(char *ifname, short flags)
{
    return set_if_flags(ifname, flags & ~IFF_UP);
}

Code copy-pasted from Linux networking documentation .代码复制粘贴自Linux 网络文档

Code to bring eth0 up:启动 eth0 的代码:

int sockfd;
struct ifreq ifr;

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0)
    return;

memset(&ifr, 0, sizeof ifr);

strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);

ifr.ifr_flags |= IFF_UP;
ioctl(sockfd, SIOCSIFFLAGS, &ifr);
int skfd = -1;      /* AF_INET socket for ioctl() calls.*/
int set_if_flags(char *ifname, short flags)
{
    struct ifreq ifr;
    int res = 0;

    ifr.ifr_flags = flags;
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ);

    if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        printf("socket error %s\n", strerror(errno));
        res = 1;
        goto out;
    }

    res = ioctl(skfd, SIOCSIFFLAGS, &ifr);
    if (res < 0) {
        printf("Interface '%s': Error: SIOCSIFFLAGS failed: %s\n",
            ifname, strerror(errno));
    } else {
        printf("Interface '%s': flags set to %04X.\n", ifname, flags);
    }
out:
    return res;
}
int set_if_up(char *ifname, short flags)
{
    return set_if_flags(ifname, flags | IFF_UP);
}

usage:用法:

set_if_up("eth0", 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Linux内核模块中的Linux Real Mode Interface - Linux Real Mode Interface in a linux kernel module 在 Linux 内核模块中获取接口掩码 - Obtain interface netmask in Linux kernel module 如何在Linux内核中以编程方式读取linux文件权限 - How to read linux file permission programmatically in linux kernel 为Linux内核开发设置Netbeans / Eclipse - Setting up Netbeans/Eclipse for Linux Kernel Development 以编程方式检查运行时是否存在Linux内核模块 - Programmatically check whether a linux kernel module exists or not at runtime 如何判断 linux 内核在哪里解析 tuntap 接口上的 MLD 连接? - How to tell where linux kernel is parsing MLD joins on tuntap interface? Linux内核模块,防止usbcore在探测后注册另一个接口 - Linux Kernel Module , prevent usbcore to registered another interface after probe 有没有办法在 Linux 中使用 C 以编程方式设置接口 MTU? - Is there a way to programmatically set an interface MTU using C in Linux? 在Linux上,TLS是由内核还是由libc(或其他语言运行时)设置的? - On Linux, is TLS set up by the kernel or by libc (or other language runtime)? linux kernel 4.12中wake_up_interruptible()的正确用法是什么? - What is the correct usage of wake_up_interruptible() in linux kernel 4.12?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM