ip_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package ip
  2. import (
  3. "net"
  4. "testing"
  5. )
  6. func TestIPInCidr(t *testing.T) {
  7. ip := NewIP()
  8. HandleIP(t, ip, "123.2.3.5", false)
  9. HandleIP(t, ip, "10.10.0.0", true)
  10. HandleIP(t, ip, "10.10.10.10", true)
  11. HandleIP(t, ip, "10.255.255.255", true)
  12. HandleIP(t, ip, "11.0.0.0", false)
  13. HandleIP(t, ip, "10.10.10.432", false)
  14. HandleIP(t, ip, "127.0.0.1", true)
  15. HandleIP(t, ip, "127.255.255.255", true)
  16. HandleIP(t, ip, "128.0.0.1", false)
  17. HandleIP(t, ip, "126.255.255.255", false)
  18. HandleIP(t, ip, "192.167.255.255", false)
  19. HandleIP(t, ip, "192.168.0.0", true)
  20. HandleIP(t, ip, "192.168.122.1", true)
  21. HandleIP(t, ip, "192.168.255.255", true)
  22. HandleIP(t, ip, "192.169.0.0", false)
  23. HandleIP(t, ip, "172.15.255.255", false)
  24. HandleIP(t, ip, "172.16.0.0", true)
  25. HandleIP(t, ip, "172.16.1.7", true)
  26. HandleIP(t, ip, "172.31.255.255", true)
  27. HandleIP(t, ip, "172.15.255.255", false)
  28. HandleIP(t, ip, "fcff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", false)
  29. HandleIP(t, ip, "fd00::1", true)
  30. HandleIP(t, ip, "fd02::1", true)
  31. HandleIP(t, ip, "fdff::1", true)
  32. HandleIP(t, ip, "fe00::1", false)
  33. }
  34. func TestNetwork(t *testing.T) {
  35. ip := NewIP()
  36. HandleNetwork(t, ip, "127.0.0.1", "127.0.0.0/8", true)
  37. HandleNetwork(t, ip, "127.244.0.1", "127.0.0.1/8", true)
  38. HandleNetwork(t, ip, "128.244.0.1", "127.0.0.1/8", false)
  39. HandleNetwork(t, ip, "10.145.32.11", "10.0.0.0/8", true)
  40. HandleNetwork(t, ip, "172.16.0.1", "172.16.0.0/12", true)
  41. HandleNetwork(t, ip, "192.168.21.44", "192.168.0.0/16", true)
  42. }
  43. func HandleNetwork(t *testing.T, privIP *IP, ip string, n string, assert bool) {
  44. _, network, _ := net.ParseCIDR(n)
  45. addr := net.ParseIP(ip)
  46. res := privIP.Network(addr)
  47. chk := (res != nil && res.String() == network.String())
  48. if chk != assert {
  49. t.Errorf("Assertion (have: %t, should be %t) failed on IP %s", chk, assert, ip)
  50. }
  51. }
  52. func HandleIP(t *testing.T, ip *IP, addr string, assert bool) {
  53. res := ip.IsPrivate(net.ParseIP(addr))
  54. if res != assert {
  55. t.Errorf("Assertion (have: %t, should be %t) failed on IP %s", res, assert, addr)
  56. }
  57. }