]> Sergey Matveev's repositories - btrtrc.git/blobdiff - ipport.go
Drop support for go 1.20
[btrtrc.git] / ipport.go
index 38036cb40c3aaf86848cbd64b90142f9ded744d0..a85a97fc10422229ba7cdaececd7fbe5d4b5abbc 100644 (file)
--- a/ipport.go
+++ b/ipport.go
@@ -3,19 +3,69 @@ package torrent
 import (
        "net"
        "strconv"
-
-       "github.com/anacrolix/missinggo"
 )
 
-type ipPort struct {
+// Extracts the port as an integer from an address string.
+func addrPortOrZero(addr net.Addr) int {
+       switch raw := addr.(type) {
+       case *net.UDPAddr:
+               return raw.Port
+       case *net.TCPAddr:
+               return raw.Port
+       default:
+               // Consider a unix socket on Windows with a name like "C:notanint".
+               _, port, err := net.SplitHostPort(addr.String())
+               if err != nil {
+                       return 0
+               }
+               i64, err := strconv.ParseUint(port, 0, 16)
+               if err != nil {
+                       return 0
+               }
+               return int(i64)
+       }
+}
+
+func addrIpOrNil(addr net.Addr) net.IP {
+       if addr == nil {
+               return nil
+       }
+       switch raw := addr.(type) {
+       case *net.UDPAddr:
+               return raw.IP
+       case *net.TCPAddr:
+               return raw.IP
+       default:
+               host, _, err := net.SplitHostPort(addr.String())
+               if err != nil {
+                       return nil
+               }
+               return net.ParseIP(host)
+       }
+}
+
+type ipPortAddr struct {
        IP   net.IP
-       Port uint16
+       Port int
+}
+
+func (ipPortAddr) Network() string {
+       return ""
 }
 
-func (me ipPort) String() string {
-       return net.JoinHostPort(me.IP.String(), strconv.FormatUint(uint64(me.Port), 10))
+func (me ipPortAddr) String() string {
+       return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
 }
 
-func ipPortFromNetAddr(na net.Addr) ipPort {
-       return ipPort{missinggo.AddrIP(na), uint16(missinggo.AddrPort(na))}
+func tryIpPortFromNetAddr(addr PeerRemoteAddr) (ipPortAddr, bool) {
+       ok := true
+       host, port, err := net.SplitHostPort(addr.String())
+       if err != nil {
+               ok = false
+       }
+       portI64, err := strconv.ParseInt(port, 10, 0)
+       if err != nil {
+               ok = false
+       }
+       return ipPortAddr{net.ParseIP(host), int(portI64)}, ok
 }