helper_posix.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2014 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 aix darwin dragonfly freebsd linux netbsd openbsd solaris windows
  5. package icmp
  6. import (
  7. "net"
  8. "strconv"
  9. "syscall"
  10. )
  11. func sockaddr(family int, address string) (syscall.Sockaddr, error) {
  12. switch family {
  13. case syscall.AF_INET:
  14. a, err := net.ResolveIPAddr("ip4", address)
  15. if err != nil {
  16. return nil, err
  17. }
  18. if len(a.IP) == 0 {
  19. a.IP = net.IPv4zero
  20. }
  21. if a.IP = a.IP.To4(); a.IP == nil {
  22. return nil, net.InvalidAddrError("non-ipv4 address")
  23. }
  24. sa := &syscall.SockaddrInet4{}
  25. copy(sa.Addr[:], a.IP)
  26. return sa, nil
  27. case syscall.AF_INET6:
  28. a, err := net.ResolveIPAddr("ip6", address)
  29. if err != nil {
  30. return nil, err
  31. }
  32. if len(a.IP) == 0 {
  33. a.IP = net.IPv6unspecified
  34. }
  35. if a.IP.Equal(net.IPv4zero) {
  36. a.IP = net.IPv6unspecified
  37. }
  38. if a.IP = a.IP.To16(); a.IP == nil || a.IP.To4() != nil {
  39. return nil, net.InvalidAddrError("non-ipv6 address")
  40. }
  41. sa := &syscall.SockaddrInet6{ZoneId: zoneToUint32(a.Zone)}
  42. copy(sa.Addr[:], a.IP)
  43. return sa, nil
  44. default:
  45. return nil, net.InvalidAddrError("unexpected family")
  46. }
  47. }
  48. func zoneToUint32(zone string) uint32 {
  49. if zone == "" {
  50. return 0
  51. }
  52. if ifi, err := net.InterfaceByName(zone); err == nil {
  53. return uint32(ifi.Index)
  54. }
  55. n, err := strconv.Atoi(zone)
  56. if err != nil {
  57. return 0
  58. }
  59. return uint32(n)
  60. }
  61. func last(s string, b byte) int {
  62. i := len(s)
  63. for i--; i >= 0; i-- {
  64. if s[i] == b {
  65. break
  66. }
  67. }
  68. return i
  69. }