有没有办法以编程方式使用C设置接口MTU?

时间:2014-07-29 22:49:30

标签: c networking mtu

目前我的程序正在调用ifconfig来执行此操作。

看起来有点乱 - 可能ifconfig不在路径上,或者在某些非标准位置。然后我需要在发生故障时检查iproute2等效物。

有没有办法用C?

以编程方式设置它?

非常感谢!

2 个答案:

答案 0 :(得分:3)

您可以在ioctl调用中设置SIOCSIFMTU字段,如下所示:

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.

上面的代码将使用ifreq结构中的ifr_mtu字段设置设备的MTU(如在ifr.name中)。

参考:http://linux.die.net/man/7/netdevice

答案 1 :(得分:2)

您也可以使用。完整示例:

#include <stdio.h>
#include <string.h>
#include <net/if.h>
#include <sys/socket.h>
#include <linux/rtnetlink.h>

#define IFACE_NAME "enp5s0"

int main(void) {
     int ret, nl_sock;
     unsigned int mtu = 8000;
     struct rtattr  *rta;
     struct {
          struct nlmsghdr nh;
          struct ifinfomsg  ifinfo;
          char   attrbuf[512];
     } req;

     nl_sock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
     if(nl_sock < 0) {
          perror("socket():");
          return -1;
     }

     memset(&req, 0, sizeof req);
     req.nh.nlmsg_len   = NLMSG_LENGTH(sizeof(struct ifinfomsg));
     req.nh.nlmsg_flags = NLM_F_REQUEST;
     req.nh.nlmsg_type  = RTM_NEWLINK; // RTM_SETLINK
     req.ifinfo.ifi_family = AF_UNSPEC;
     req.ifinfo.ifi_index  = if_nametoindex(IFACE_NAME);
     if(!req.ifinfo.ifi_index) {
          perror("if_nametoindex():");
          return -1;
     }
     printf("%s index: %d\n", IFACE_NAME, req.ifinfo.ifi_index);
     req.ifinfo.ifi_change = 0xffffffff;
     rta = (struct rtattr *)(((char *) &req) + NLMSG_ALIGN(req.nh.nlmsg_len));
     rta->rta_type = IFLA_MTU;
     rta->rta_len = RTA_LENGTH(sizeof(unsigned int));
     req.nh.nlmsg_len = NLMSG_ALIGN(req.nh.nlmsg_len) + RTA_LENGTH(sizeof mtu);
     memcpy(RTA_DATA(rta), &mtu, sizeof mtu);

     ret = send(nl_sock, &req, req.nh.nlmsg_len, 0);
     if(ret < 0) {
          perror("send():");
          return -1;
     }

     return 0;
}

另请阅读:rtnetlink(3)rtnetlink(7)