udpsock.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package net
  5. // UDPAddr represents the address of a UDP end point.
  6. type UDPAddr struct {
  7. IP IP
  8. Port int
  9. Zone string // IPv6 scoped addressing zone
  10. }
  11. // Network returns the address's network name, "udp".
  12. func (a *UDPAddr) Network() string { return "udp" }
  13. func (a *UDPAddr) String() string {
  14. if a == nil {
  15. return "<nil>"
  16. }
  17. ip := ipEmptyString(a.IP)
  18. if a.Zone != "" {
  19. return JoinHostPort(ip+"%"+a.Zone, itoa(a.Port))
  20. }
  21. return JoinHostPort(ip, itoa(a.Port))
  22. }
  23. func (a *UDPAddr) toAddr() Addr {
  24. if a == nil {
  25. return nil
  26. }
  27. return a
  28. }
  29. // ResolveUDPAddr parses addr as a UDP address of the form "host:port"
  30. // or "[ipv6-host%zone]:port" and resolves a pair of domain name and
  31. // port name on the network net, which must be "udp", "udp4" or
  32. // "udp6". A literal address or host name for IPv6 must be enclosed
  33. // in square brackets, as in "[::1]:80", "[ipv6-host]:http" or
  34. // "[ipv6-host%zone]:80".
  35. func ResolveUDPAddr(net, addr string) (*UDPAddr, error) {
  36. switch net {
  37. case "udp", "udp4", "udp6":
  38. case "": // a hint wildcard for Go 1.0 undocumented behavior
  39. net = "udp"
  40. default:
  41. return nil, UnknownNetworkError(net)
  42. }
  43. a, err := resolveInternetAddr(net, addr, noDeadline)
  44. if err != nil {
  45. return nil, err
  46. }
  47. return a.toAddr().(*UDPAddr), nil
  48. }