...

Source file src/golang.conradwood.net/go-easyops/linux/myip.go

Documentation: golang.conradwood.net/go-easyops/linux

     1  package linux
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"os"
     7  	"strings"
     8  )
     9  
    10  const (
    11  	chatty_myip = false
    12  )
    13  
    14  var (
    15  	pref_nic_if = []string{"dummy", "wg", "tun"}
    16  )
    17  
    18  func fail(txt string, err error) {
    19  	if err == nil {
    20  		return
    21  	}
    22  	fmt.Printf("ERROR: %s: %s\n", txt, err)
    23  	os.Exit(10)
    24  }
    25  
    26  // find my ip (which is not localhost)
    27  func (*linux) MyIP() string {
    28  	ifaces, err := net.Interfaces()
    29  	fail("could not get interfaces", err)
    30  	var cur_ip *net.IPNet
    31  	cur_pref := 0
    32  
    33  	for _, iface := range ifaces {
    34  		if chatty_myip {
    35  			fmt.Printf("Iface %s:\n", iface.Name)
    36  		}
    37  		addrs, err := iface.Addrs()
    38  		fail("cannot get interface address", err)
    39  		for _, adr := range addrs {
    40  			use := true
    41  			ipnet, ok := adr.(*net.IPNet)
    42  			if !ok {
    43  				continue
    44  			}
    45  			s := ""
    46  			if ipnet.IP.IsLoopback() {
    47  				use = false
    48  				s = " [loopback]"
    49  			}
    50  			if ipnet.IP.To4() == nil {
    51  				use = false
    52  				s = " [not ip4]"
    53  			}
    54  			if chatty_myip {
    55  				fmt.Printf("   %s%s\n", adr.String(), s)
    56  			}
    57  			if use {
    58  				if cur_ip == nil || nic_name_pref(iface.Name) > cur_pref {
    59  					cur_ip = ipnet
    60  				}
    61  			}
    62  		}
    63  	}
    64  	if cur_ip != nil {
    65  		return cur_ip.IP.String()
    66  	}
    67  	return ""
    68  }
    69  
    70  func nic_name_pref(name string) int {
    71  	for i, n := range pref_nic_if {
    72  		if strings.HasPrefix(name, n) {
    73  			return i + 1
    74  		}
    75  	}
    76  	return len(pref_nic_if) + 2
    77  }
    78  

View as plain text