util.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package iputil
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "net"
  6. )
  7. type VpnIp uint32
  8. const maxIPv4StringLen = len("255.255.255.255")
  9. func (ip VpnIp) String() string {
  10. b := make([]byte, maxIPv4StringLen)
  11. n := ubtoa(b, 0, byte(ip>>24))
  12. b[n] = '.'
  13. n++
  14. n += ubtoa(b, n, byte(ip>>16&255))
  15. b[n] = '.'
  16. n++
  17. n += ubtoa(b, n, byte(ip>>8&255))
  18. b[n] = '.'
  19. n++
  20. n += ubtoa(b, n, byte(ip&255))
  21. return string(b[:n])
  22. }
  23. func (ip VpnIp) MarshalJSON() ([]byte, error) {
  24. return []byte(fmt.Sprintf("\"%s\"", ip.String())), nil
  25. }
  26. func (ip VpnIp) ToIP() net.IP {
  27. nip := make(net.IP, 4)
  28. binary.BigEndian.PutUint32(nip, uint32(ip))
  29. return nip
  30. }
  31. func Ip2VpnIp(ip []byte) VpnIp {
  32. if len(ip) == 16 {
  33. return VpnIp(binary.BigEndian.Uint32(ip[12:16]))
  34. }
  35. return VpnIp(binary.BigEndian.Uint32(ip))
  36. }
  37. // ubtoa encodes the string form of the integer v to dst[start:] and
  38. // returns the number of bytes written to dst. The caller must ensure
  39. // that dst has sufficient length.
  40. func ubtoa(dst []byte, start int, v byte) int {
  41. if v < 10 {
  42. dst[start] = v + '0'
  43. return 1
  44. } else if v < 100 {
  45. dst[start+1] = v%10 + '0'
  46. dst[start] = v/10 + '0'
  47. return 2
  48. }
  49. dst[start+2] = v%10 + '0'
  50. dst[start+1] = (v/10)%10 + '0'
  51. dst[start] = v/100 + '0'
  52. return 3
  53. }