github.com/vipernet-xyz/tendermint-core@v0.32.0/libs/net/net.go (about) 1 package net 2 3 import ( 4 "net" 5 "strings" 6 ) 7 8 // Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol, 9 // eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock" 10 func Connect(protoAddr string) (net.Conn, error) { 11 proto, address := ProtocolAndAddress(protoAddr) 12 conn, err := net.Dial(proto, address) 13 return conn, err 14 } 15 16 // ProtocolAndAddress splits an address into the protocol and address components. 17 // For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080". 18 // If the address has no protocol prefix, the default is "tcp". 19 func ProtocolAndAddress(listenAddr string) (string, string) { 20 protocol, address := "tcp", listenAddr 21 parts := strings.SplitN(address, "://", 2) 22 if len(parts) == 2 { 23 protocol, address = parts[0], parts[1] 24 } 25 return protocol, address 26 } 27 28 // GetFreePort gets a free port from the operating system. 29 // Ripped from https://github.com/phayes/freeport. 30 // BSD-licensed. 31 func GetFreePort() (int, error) { 32 addr, err := net.ResolveTCPAddr("tcp", "localhost:0") 33 if err != nil { 34 return 0, err 35 } 36 37 l, err := net.ListenTCP("tcp", addr) 38 if err != nil { 39 return 0, err 40 } 41 defer l.Close() 42 return l.Addr().(*net.TCPAddr).Port, nil 43 }