Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux programmatically up/down an interface kernel

What is the programmatic way of enabling or disabling an interface in kernel space? What should be done?

like image 931
whoi Avatar asked May 02 '11 14:05

whoi


People also ask

What is netdevice in linux?

The net device structure, defined in file linux/include/netdevice. h, is the data structure that defines an instance of a network interface. It tracks the state information of all the network interface devices attached to the TCP/IP stack.

Which command will show you the interface used to reach an external address?

I use netstat -Wcatnp . You should try this command.

How do I use an interface in Linux?

First, we enable the network interface eth0 at boot time. Secondly, we set a static IP address, network, and gateway. Next, we add two DNS servers. In addition, we put a script to launch a firewall before starting the interface.


2 Answers

...by using IOCTL's...

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.:

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.

like image 193
Andrejs Cainikovs Avatar answered Oct 01 '22 08:10

Andrejs Cainikovs


Code to bring eth0 up:

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);
like image 29
Tarc Avatar answered Oct 01 '22 08:10

Tarc