Linux 以编程方式启动/关闭接口内核
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5858655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux programmatically up/down an interface kernel
提问by whoi
What is the programmatic way of enabling or disabling an interface in kernel space? What should be done?
在内核空间中启用或禁用接口的编程方式是什么?应该做什么?
采纳答案by Andrejs Cainikovs
...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, i.e.:
...设置或取消设置 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 网络文档复制粘贴的代码。
回答by Tarc
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);
回答by Mahdi Mohammadi
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);