blob: 472bd4ef2b92a9adbb4e7dc9b6a9c6e8f8a442c2 [file] [log] [blame]
Daniel Drowna45056e2012-03-23 10:42:54 -05001/*
2 * Copyright 2011 Daniel Drown
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * mtu.c - get interface mtu
17 */
18
Daniel Drowna45056e2012-03-23 10:42:54 -050019#include <net/if.h>
junyulaic4e591a2018-11-26 22:36:10 +090020#include <stdlib.h>
21#include <string.h>
22#include <sys/ioctl.h>
23#include <sys/socket.h>
24#include <sys/types.h>
Maciej Żenczykowski60bce372019-04-09 01:58:52 -070025#include <unistd.h>
Daniel Drowna45056e2012-03-23 10:42:54 -050026
27#include "mtu.h"
28
29/* function: getifmtu
30 * returns the interface mtu or -1 on failure
31 * ifname - interface name
32 */
33int getifmtu(const char *ifname) {
34 int fd;
35 struct ifreq if_mtu;
36
Maciej Żenczykowski60bce372019-04-09 01:58:52 -070037 fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
junyulaic4e591a2018-11-26 22:36:10 +090038 if (fd < 0) {
Daniel Drowna45056e2012-03-23 10:42:54 -050039 return -1;
40 }
41 strncpy(if_mtu.ifr_name, ifname, IFNAMSIZ);
42 if_mtu.ifr_name[IFNAMSIZ - 1] = '\0';
junyulaic4e591a2018-11-26 22:36:10 +090043 if (ioctl(fd, SIOCGIFMTU, &if_mtu) < 0) {
Maciej Żenczykowski60bce372019-04-09 01:58:52 -070044 close(fd);
Daniel Drowna45056e2012-03-23 10:42:54 -050045 return -1;
46 }
Maciej Żenczykowski60bce372019-04-09 01:58:52 -070047 close(fd);
Daniel Drowna45056e2012-03-23 10:42:54 -050048 return if_mtu.ifr_mtu;
49}