Daniel Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 1 | /* |
| 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 Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 19 | #include <net/if.h> |
junyulai | c4e591a | 2018-11-26 22:36:10 +0900 | [diff] [blame] | 20 | #include <stdlib.h> |
| 21 | #include <string.h> |
| 22 | #include <sys/ioctl.h> |
| 23 | #include <sys/socket.h> |
| 24 | #include <sys/types.h> |
Maciej Żenczykowski | 60bce37 | 2019-04-09 01:58:52 -0700 | [diff] [blame] | 25 | #include <unistd.h> |
Daniel Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 26 | |
| 27 | #include "mtu.h" |
| 28 | |
| 29 | /* function: getifmtu |
| 30 | * returns the interface mtu or -1 on failure |
| 31 | * ifname - interface name |
| 32 | */ |
| 33 | int getifmtu(const char *ifname) { |
| 34 | int fd; |
| 35 | struct ifreq if_mtu; |
| 36 | |
Maciej Żenczykowski | 60bce37 | 2019-04-09 01:58:52 -0700 | [diff] [blame] | 37 | fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); |
junyulai | c4e591a | 2018-11-26 22:36:10 +0900 | [diff] [blame] | 38 | if (fd < 0) { |
Daniel Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 39 | return -1; |
| 40 | } |
| 41 | strncpy(if_mtu.ifr_name, ifname, IFNAMSIZ); |
| 42 | if_mtu.ifr_name[IFNAMSIZ - 1] = '\0'; |
junyulai | c4e591a | 2018-11-26 22:36:10 +0900 | [diff] [blame] | 43 | if (ioctl(fd, SIOCGIFMTU, &if_mtu) < 0) { |
Maciej Żenczykowski | 60bce37 | 2019-04-09 01:58:52 -0700 | [diff] [blame] | 44 | close(fd); |
Daniel Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 45 | return -1; |
| 46 | } |
Maciej Żenczykowski | 60bce37 | 2019-04-09 01:58:52 -0700 | [diff] [blame] | 47 | close(fd); |
Daniel Drown | a45056e | 2012-03-23 10:42:54 -0500 | [diff] [blame] | 48 | return if_mtu.ifr_mtu; |
| 49 | } |