addr.go 748 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package missinggo
  2. import (
  3. "net"
  4. "strconv"
  5. )
  6. // Extracts the port as an integer from an address string.
  7. func AddrPort(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. _, port, err := net.SplitHostPort(addr.String())
  15. if err != nil {
  16. panic(err)
  17. }
  18. i64, err := strconv.ParseInt(port, 0, 0)
  19. if err != nil {
  20. panic(err)
  21. }
  22. return int(i64)
  23. }
  24. }
  25. func AddrIP(addr net.Addr) net.IP {
  26. if addr == nil {
  27. return nil
  28. }
  29. switch raw := addr.(type) {
  30. case *net.UDPAddr:
  31. return raw.IP
  32. case *net.TCPAddr:
  33. return raw.IP
  34. default:
  35. host, _, err := net.SplitHostPort(addr.String())
  36. if err != nil {
  37. panic(err)
  38. }
  39. return net.ParseIP(host)
  40. }
  41. }