github.com/rochacon/deis@v1.0.2-0.20150903015341-6839b592a1ff/mesos/pkg/net/net.go (about) 1 package net 2 3 import ( 4 "errors" 5 "net" 6 "strconv" 7 "strings" 8 "time" 9 ) 10 11 // InterfaceIPAddress is used to know the interface and ip address in the sytem 12 type InterfaceIPAddress struct { 13 Iface string 14 IP string 15 } 16 17 // WaitForPort wait for successful network connection 18 func WaitForPort(proto string, ip string, port int, timeout time.Duration) error { 19 for { 20 con, err := net.DialTimeout(proto, ip+":"+strconv.Itoa(port), timeout) 21 if err == nil { 22 con.Close() 23 break 24 } 25 } 26 27 return nil 28 } 29 30 // RandomPort return a random not used TCP port 31 func RandomPort(proto string) (int, error) { 32 switch proto { 33 case "tcp": 34 l, _ := net.Listen(proto, "127.0.0.1:0") 35 defer l.Close() 36 port := l.Addr() 37 lPort, _ := strconv.Atoi(strings.Split(port.String(), ":")[1]) 38 return lPort, nil 39 case "udp": 40 addr, _ := net.ResolveUDPAddr(proto, "127.0.0.1:0") 41 l, _ := net.ListenUDP(proto, addr) 42 defer l.Close() 43 return addr.Port, nil 44 default: 45 return -1, errors.New("invalid protocol") 46 } 47 } 48 49 // GetNetworkInterfaces return the list of 50 // network interfaces and IP address 51 func GetNetworkInterfaces() []InterfaceIPAddress { 52 result := []InterfaceIPAddress{} 53 54 interfaces, _ := net.Interfaces() 55 for _, inter := range interfaces { 56 if addrs, err := inter.Addrs(); err == nil { 57 for _, addr := range addrs { 58 result = append(result, InterfaceIPAddress{inter.Name, addr.String()}) 59 } 60 } 61 } 62 63 return result 64 } 65 66 // ParseIP parses s as an IP address 67 func ParseIP(s string) net.IP { 68 return net.ParseIP(s) 69 }