addr.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package ice
  4. import (
  5. "net"
  6. )
  7. func parseMulticastAnswerAddr(in net.Addr) (net.IP, bool) {
  8. switch addr := in.(type) {
  9. case *net.IPAddr:
  10. return addr.IP, true
  11. case *net.UDPAddr:
  12. return addr.IP, true
  13. case *net.TCPAddr:
  14. return addr.IP, true
  15. }
  16. return nil, false
  17. }
  18. func parseAddr(in net.Addr) (net.IP, int, NetworkType, bool) {
  19. switch addr := in.(type) {
  20. case *net.UDPAddr:
  21. return addr.IP, addr.Port, NetworkTypeUDP4, true
  22. case *net.TCPAddr:
  23. return addr.IP, addr.Port, NetworkTypeTCP4, true
  24. }
  25. return nil, 0, 0, false
  26. }
  27. func createAddr(network NetworkType, ip net.IP, port int) net.Addr {
  28. switch {
  29. case network.IsTCP():
  30. return &net.TCPAddr{IP: ip, Port: port}
  31. default:
  32. return &net.UDPAddr{IP: ip, Port: port}
  33. }
  34. }
  35. func addrEqual(a, b net.Addr) bool {
  36. aIP, aPort, aType, aOk := parseAddr(a)
  37. if !aOk {
  38. return false
  39. }
  40. bIP, bPort, bType, bOk := parseAddr(b)
  41. if !bOk {
  42. return false
  43. }
  44. return aType == bType && aIP.Equal(bIP) && aPort == bPort
  45. }
  46. // AddrPort is an IP and a port number.
  47. type AddrPort [18]byte
  48. func toAddrPort(addr net.Addr) AddrPort {
  49. var ap AddrPort
  50. switch addr := addr.(type) {
  51. case *net.UDPAddr:
  52. copy(ap[:16], addr.IP.To16())
  53. ap[16] = uint8(addr.Port >> 8)
  54. ap[17] = uint8(addr.Port)
  55. case *net.TCPAddr:
  56. copy(ap[:16], addr.IP.To16())
  57. ap[16] = uint8(addr.Port >> 8)
  58. ap[17] = uint8(addr.Port)
  59. }
  60. return ap
  61. }