ipport.go 1.3 KB

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