How to install the network interface MTU in Linux in C language?

  • I guessed: ifreq opts; opts.ifr_ifru.ifru_mtu = 1500; if (ioctl (m_inSocket, SIOCSIFFLAGS, & opts) <0) {throw SocketException (errno); } Right? - cipher_web
  • trow - C ++ operator, not C - sercxjo
  • It’s clear that it’s not the language tools, but Linux is written in C and it’s not hard to get C from C ++! - cipher_web

1 answer 1

I advise you to take the source code iproute2, the file iplink.c

 #include <stdio.h> #include <sys/socket.h> #include <linux/sockios.h> #include <linux/if.h> #include <sys/ioctl.h> #include <string.h> #include <errno.h> static int get_ctl_fd(void) { int s_errno; int fd; fd = socket(PF_INET, SOCK_DGRAM, 0); if (fd >= 0) return fd; s_errno = errno; fd = socket(PF_PACKET, SOCK_DGRAM, 0); if (fd >= 0) return fd; fd = socket(PF_INET6, SOCK_DGRAM, 0); if (fd >= 0) return fd; errno = s_errno; perror("Cannot create control socket"); return -1; } static int set_mtu(const char *dev, int mtu) { struct ifreq ifr; int s; s = get_ctl_fd(); if (s < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, dev, IFNAMSIZ); ifr.ifr_mtu = mtu; if (ioctl(s, SIOCSIFMTU, &ifr) < 0) { perror("SIOCSIFMTU"); close(s); return -1; } close(s); return 0; } 
  • Yes, much like the truth, I can not check it yet. Thank! - cipher_web
  • @cipher_web, works for me - sercxjo
  • Well, it means it works ... - cipher_web
  • Additional comments - the question is: in what units is MTU specified, when setting int 1500, the interface crashes tightly (including the browser) - cipher_web
  • @cipher_web, MTU is specified in bytes, this is the packet size at the data link layer, which is lower than IP. 1500 is the standard size for Ethernet. If the MTU returns to the previous value, the interface does not come to life? - sercxjo