github.com/anacrolix/torrent@v1.61.0/ipport.go (about)

     1  package torrent
     2  
     3  import (
     4  	"net"
     5  	"strconv"
     6  )
     7  
     8  // Extracts the port as an integer from an address string.
     9  func addrPortOrZero(addr net.Addr) int {
    10  	switch raw := addr.(type) {
    11  	case *net.UDPAddr:
    12  		return raw.Port
    13  	case *net.TCPAddr:
    14  		return raw.Port
    15  	default:
    16  		// Consider a unix socket on Windows with a name like "C:notanint".
    17  		_, port, err := net.SplitHostPort(addr.String())
    18  		if err != nil {
    19  			return 0
    20  		}
    21  		i64, err := strconv.ParseUint(port, 0, 16)
    22  		if err != nil {
    23  			return 0
    24  		}
    25  		return int(i64)
    26  	}
    27  }
    28  
    29  func addrIpOrNil(addr net.Addr) net.IP {
    30  	if addr == nil {
    31  		return nil
    32  	}
    33  	switch raw := addr.(type) {
    34  	case *net.UDPAddr:
    35  		return raw.IP
    36  	case *net.TCPAddr:
    37  		return raw.IP
    38  	default:
    39  		host, _, err := net.SplitHostPort(addr.String())
    40  		if err != nil {
    41  			return nil
    42  		}
    43  		return net.ParseIP(host)
    44  	}
    45  }
    46  
    47  type ipPortAddr struct {
    48  	IP   net.IP
    49  	Port int
    50  }
    51  
    52  func (ipPortAddr) Network() string {
    53  	return ""
    54  }
    55  
    56  func (me ipPortAddr) String() string {
    57  	return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
    58  }
    59  
    60  func tryIpPortFromNetAddr(addr PeerRemoteAddr) (ipPortAddr, bool) {
    61  	ok := true
    62  	host, port, err := net.SplitHostPort(addr.String())
    63  	if err != nil {
    64  		ok = false
    65  	}
    66  	portI64, err := strconv.ParseInt(port, 10, 0)
    67  	if err != nil {
    68  		ok = false
    69  	}
    70  	return ipPortAddr{net.ParseIP(host), int(portI64)}, ok
    71  }