Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to programmatically set an interface MTU using C in Linux?

At the moment my program is making a system() call to ifconfig to do this.

It seems a bit messy - maybe ifconfig is not on the path, or in some non-standard location. And then I'd need to check for the iproute2 equivalent in case of failure.

Is there a way to set this programmatically using C?

like image 697
James Avatar asked Mar 19 '23 21:03

James


1 Answers

You can set the SIOCSIFMTU field in an ioctl call, something like this:

struct ifreq ifr; 
ifr.ifr_addr.sa_family = AF_INET;//address family
strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name));//interface name where you want to set the MTU
ifr.ifr_mtu = 9100; //your MTU size here
if (ioctl(sockfd, SIOCSIFMTU, (caddr_t)&ifr) < 0)
  //failed to set MTU. handle error.

The above code will set the MTU of a device(as in ifr.name) using ifr_mtu field in the ifreq structure.

Refer: http://linux.die.net/man/7/netdevice

like image 135
askmish Avatar answered Apr 06 '23 10:04

askmish