sockopt_asmreq.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2012 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. // +build darwin dragonfly freebsd netbsd openbsd solaris windows
  5. package ipv4
  6. import "net"
  7. func setIPMreqInterface(mreq *ipMreq, ifi *net.Interface) error {
  8. if ifi == nil {
  9. return nil
  10. }
  11. ifat, err := ifi.Addrs()
  12. if err != nil {
  13. return err
  14. }
  15. for _, ifa := range ifat {
  16. switch ifa := ifa.(type) {
  17. case *net.IPAddr:
  18. if ip := ifa.IP.To4(); ip != nil {
  19. copy(mreq.Interface[:], ip)
  20. return nil
  21. }
  22. case *net.IPNet:
  23. if ip := ifa.IP.To4(); ip != nil {
  24. copy(mreq.Interface[:], ip)
  25. return nil
  26. }
  27. }
  28. }
  29. return errNoSuchInterface
  30. }
  31. func netIP4ToInterface(ip net.IP) (*net.Interface, error) {
  32. ift, err := net.Interfaces()
  33. if err != nil {
  34. return nil, err
  35. }
  36. for _, ifi := range ift {
  37. ifat, err := ifi.Addrs()
  38. if err != nil {
  39. return nil, err
  40. }
  41. for _, ifa := range ifat {
  42. switch ifa := ifa.(type) {
  43. case *net.IPAddr:
  44. if ip.Equal(ifa.IP) {
  45. return &ifi, nil
  46. }
  47. case *net.IPNet:
  48. if ip.Equal(ifa.IP) {
  49. return &ifi, nil
  50. }
  51. }
  52. }
  53. }
  54. return nil, errNoSuchInterface
  55. }
  56. func netInterfaceToIP4(ifi *net.Interface) (net.IP, error) {
  57. if ifi == nil {
  58. return net.IPv4zero.To4(), nil
  59. }
  60. ifat, err := ifi.Addrs()
  61. if err != nil {
  62. return nil, err
  63. }
  64. for _, ifa := range ifat {
  65. switch ifa := ifa.(type) {
  66. case *net.IPAddr:
  67. if ip := ifa.IP.To4(); ip != nil {
  68. return ip, nil
  69. }
  70. case *net.IPNet:
  71. if ip := ifa.IP.To4(); ip != nil {
  72. return ip, nil
  73. }
  74. }
  75. }
  76. return nil, errNoSuchInterface
  77. }