github.com/fafucoder/cilium@v1.6.11/pkg/mtu/detect_linux.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 // 15 // +build linux 16 17 package mtu 18 19 import ( 20 "fmt" 21 "net" 22 23 "github.com/vishvananda/netlink" 24 ) 25 26 const ( 27 externalProbeIPv4 = "1.1.1.1" 28 externalProbeIPv6 = "2606:4700:4700::1111" 29 ) 30 31 func getRoute(externalProbe string) ([]netlink.Route, error) { 32 ip := net.ParseIP(externalProbe) 33 if ip == nil { 34 return nil, fmt.Errorf("unable to parse IP %s", externalProbe) 35 } 36 37 routes, err := netlink.RouteGet(ip) 38 if err != nil { 39 return nil, fmt.Errorf("unable to lookup route to %s: %s", externalProbe, err) 40 } 41 42 if len(routes) == 0 { 43 return nil, fmt.Errorf("no route to %s", externalProbe) 44 } 45 46 return routes, nil 47 } 48 49 func autoDetect() (int, error) { 50 var routes []netlink.Route 51 var err error 52 53 routes, err = getRoute(externalProbeIPv4) 54 if err != nil { 55 prevErr := err 56 routes, err = getRoute(externalProbeIPv6) 57 if err != nil { 58 return 0, fmt.Errorf("%v, %v", err.Error(), prevErr.Error()) 59 } 60 } 61 62 link, err := netlink.LinkByIndex(routes[0].LinkIndex) 63 if err != nil { 64 return 0, fmt.Errorf("unable to find interface of default route: %s", err) 65 } 66 67 if mtu := link.Attrs().MTU; mtu != 0 { 68 log.Infof("Detected MTU %d", mtu) 69 return mtu, nil 70 } 71 72 return EthernetMTU, nil 73 }