1
0

host.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2013, Cong Ding. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // Author: Cong Ding <dinggnu@gmail.com>
  16. package stun
  17. import (
  18. "net"
  19. "strconv"
  20. )
  21. // Host defines the network address including address family, IP address and port.
  22. type Host struct {
  23. family uint16
  24. ip string
  25. port uint16
  26. }
  27. func newHostFromStr(s string) *Host {
  28. udpAddr, err := net.ResolveUDPAddr("udp", s)
  29. if err != nil {
  30. return nil
  31. }
  32. host := new(Host)
  33. if udpAddr.IP.To4() != nil {
  34. host.family = attributeFamilyIPv4
  35. } else {
  36. host.family = attributeFamilyIPV6
  37. }
  38. host.ip = udpAddr.IP.String()
  39. host.port = uint16(udpAddr.Port)
  40. return host
  41. }
  42. // Family returns the family type of a host (IPv4 or IPv6).
  43. func (h *Host) Family() uint16 {
  44. return h.family
  45. }
  46. // IP returns the internet protocol address of the host.
  47. func (h *Host) IP() string {
  48. return h.ip
  49. }
  50. // Port returns the port number of the host.
  51. func (h *Host) Port() uint16 {
  52. return h.port
  53. }
  54. // TransportAddr returns the transport layer address of the host.
  55. func (h *Host) TransportAddr() string {
  56. return net.JoinHostPort(h.ip, strconv.Itoa(int(h.port)))
  57. }
  58. // String returns the string representation of the host address.
  59. func (h *Host) String() string {
  60. return h.TransportAddr()
  61. }