tnet.nim 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. discard """
  2. outputsub: ""
  3. """
  4. import net, nativesockets
  5. import unittest
  6. suite "isIpAddress tests":
  7. test "127.0.0.1 is valid":
  8. check isIpAddress("127.0.0.1") == true
  9. test "ipv6 localhost is valid":
  10. check isIpAddress("::1") == true
  11. test "fqdn is not an ip address":
  12. check isIpAddress("example.com") == false
  13. test "random string is not an ipaddress":
  14. check isIpAddress("foo bar") == false
  15. test "5127.0.0.1 is invalid":
  16. check isIpAddress("5127.0.0.1") == false
  17. test "ipv6 is valid":
  18. check isIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652") == true
  19. test "invalid ipv6":
  20. check isIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652") == false
  21. suite "parseIpAddress tests":
  22. test "127.0.0.1 is valid":
  23. discard parseIpAddress("127.0.0.1")
  24. test "ipv6 localhost is valid":
  25. discard parseIpAddress("::1")
  26. test "fqdn is not an ip address":
  27. expect(ValueError):
  28. discard parseIpAddress("example.com")
  29. test "random string is not an ipaddress":
  30. expect(ValueError):
  31. discard parseIpAddress("foo bar")
  32. test "ipv6 is valid":
  33. discard parseIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652")
  34. test "invalid ipv6":
  35. expect(ValueError):
  36. discard parseIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652")
  37. block: # "IpAddress/Sockaddr conversion"
  38. proc test(ipaddrstr: string) =
  39. var ipaddr_1 = parseIpAddress(ipaddrstr)
  40. # echo ipaddrstr, " ", $ipaddr_1
  41. doAssert($ipaddrstr == $ipaddr_1)
  42. var sockaddr: Sockaddr_storage
  43. var socklen: Socklen
  44. var ipaddr_2: IpAddress
  45. var port_2: Port
  46. toSockAddr(ipaddr_1, Port(0), sockaddr, socklen)
  47. fromSockAddr(sockaddr, socklen, ipaddr_2, port_2)
  48. doAssert(ipaddrstr == $ipaddr_1)
  49. doAssert(ipaddr_1 == ipaddr_2)
  50. doAssert($ipaddr_1 == $ipaddr_2)
  51. if sockaddr.ss_family.cint == AF_INET.toInt:
  52. var sockaddr4: Sockaddr_in
  53. copyMem(addr sockaddr4, addr sockaddr, sizeof(sockaddr4))
  54. fromSockAddr(sockaddr4, socklen, ipaddr_2, port_2)
  55. elif sockaddr.ss_family.cint == AF_INET6.toInt:
  56. var sockaddr6: Sockaddr_in6
  57. copyMem(addr sockaddr6, addr sockaddr, sizeof(sockaddr6))
  58. fromSockAddr(sockaddr6, socklen, ipaddr_2, port_2)
  59. doAssert(ipaddr_1 == ipaddr_2)
  60. doAssert($ipaddr_1 == $ipaddr_2)
  61. # ipv6 address of example.com
  62. test("2606:2800:220:1:248:1893:25c8:1946")
  63. # ipv6 address of localhost
  64. test("::1")
  65. # ipv4 address of example.com
  66. test("93.184.216.34")
  67. # ipv4 address of localhost
  68. test("127.0.0.1")