From: Matt Joiner Date: Mon, 17 Nov 2014 03:20:49 +0000 (-0600) Subject: Add util AddrIP and AddrPort functions X-Git-Tag: v1.0.0~1536 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=34a47a100e8915f7271e40ec41ce0efe3e75a4ba;p=btrtrc.git Add util AddrIP and AddrPort functions --- diff --git a/client.go b/client.go index 58458087..401f5efd 100644 --- a/client.go +++ b/client.go @@ -805,15 +805,7 @@ type peerExchangeMessage struct { // Extracts the port as an integer from an address string. func addrPort(addr net.Addr) int { - _, port, err := net.SplitHostPort(addr.String()) - if err != nil { - panic(err) - } - i64, err := strconv.ParseInt(port, 0, 0) - if err != nil { - panic(err) - } - return int(i64) + return AddrPort(addr) } // Processes incoming bittorrent messages. The client lock is held upon entry diff --git a/dht/dht.go b/dht/dht.go index 9118df71..5f671e60 100644 --- a/dht/dht.go +++ b/dht/dht.go @@ -487,14 +487,14 @@ func (ni *NodeInfo) PutCompact(b []byte) error { if n := copy(b[:], ni.ID[:]); n != 20 { panic(n) } - ip := ni.Addr.IP.To4() + ip := util.AddrIP(ni.Addr).To4() if len(ip) != 4 { panic(ip) } if n := copy(b[20:], ip); n != 4 { panic(n) } - binary.BigEndian.PutUint16(b[24:], uint16(ni.Addr.Port)) + binary.BigEndian.PutUint16(b[24:], uint16(util.AddrPort(ni.Addr))) return nil } @@ -651,7 +651,7 @@ func (s *Server) liftNodes(d Msg) { // log.Print(err) } else { for _, cni := range r.Nodes { - if cni.Addr.Port == 0 { + if util.AddrPort(cni.Addr) == 0 { // TODO: Why would people even do this? continue } diff --git a/util/addr.go b/util/addr.go new file mode 100644 index 00000000..a91dec3f --- /dev/null +++ b/util/addr.go @@ -0,0 +1,27 @@ +package util + +import ( + "net" + "strconv" +) + +// Extracts the port as an integer from an address string. +func AddrPort(addr net.Addr) int { + _, port, err := net.SplitHostPort(addr.String()) + if err != nil { + panic(err) + } + i64, err := strconv.ParseInt(port, 0, 0) + if err != nil { + panic(err) + } + return int(i64) +} + +func AddrIP(addr net.Addr) net.IP { + host, _, err := net.SplitHostPort(addr.String()) + if err != nil { + panic(err) + } + return net.ParseIP(host) +}