github.com/devops-filetransfer/sshego@v7.0.4+incompatible/ipaddr.go (about)

     1  package sshego
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"regexp"
     7  	"strconv"
     8  )
     9  
    10  var validIPv4addr = regexp.MustCompile(`^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$`)
    11  
    12  var privateIPv4addr = regexp.MustCompile(`(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)`)
    13  
    14  // IsRoutableIPv4 returns true if the string in ip represents an IPv4 address that is not
    15  // private. See http://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
    16  // for the numeric ranges that are private. 127.0.0.1, 192.168.0.1, and 172.16.0.1 are
    17  // examples of non-routables IP addresses.
    18  func IsRoutableIPv4(ip string) bool {
    19  	match := privateIPv4addr.FindStringSubmatch(ip)
    20  	if match != nil {
    21  		return false
    22  	}
    23  	return true
    24  }
    25  
    26  // GetExternalIP tries to determine the external IP address
    27  // used on this host.
    28  func GetExternalIP() string {
    29  	addrs, err := net.InterfaceAddrs()
    30  	if err != nil {
    31  		panic(err)
    32  	}
    33  
    34  	valid := []string{}
    35  
    36  	for _, a := range addrs {
    37  		if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
    38  			addr := ipnet.IP.String()
    39  			match := validIPv4addr.FindStringSubmatch(addr)
    40  			if match != nil {
    41  				if addr != "127.0.0.1" {
    42  					valid = append(valid, addr)
    43  				}
    44  			}
    45  		}
    46  	}
    47  	switch len(valid) {
    48  	case 0:
    49  		return "127.0.0.1"
    50  	case 1:
    51  		return valid[0]
    52  	default:
    53  		// try to get a routable ip if possible.
    54  		for _, ip := range valid {
    55  			if IsRoutableIPv4(ip) {
    56  				return ip
    57  			}
    58  		}
    59  		// give up, just return the first.
    60  		return valid[0]
    61  	}
    62  }
    63  
    64  func SplitHostPort(hostport string) (host string, port int64, err error) {
    65  	sPort := ""
    66  	host, sPort, err = net.SplitHostPort(hostport)
    67  	if err != nil {
    68  		err = fmt.Errorf("bad addr '%s': net.SplitHostPort() gave: %s", hostport, err)
    69  		return
    70  	}
    71  	if host == "" {
    72  		host = "127.0.0.1"
    73  	}
    74  	if len(sPort) == 0 {
    75  		err = fmt.Errorf("no port found in '%s'", hostport)
    76  		return
    77  	}
    78  	var prt uint64
    79  	prt, err = strconv.ParseUint(sPort, 10, 64)
    80  	if err != nil {
    81  		return
    82  	}
    83  	port = int64(prt)
    84  	return
    85  }