1. package main
    2. import (
    3. "fmt"
    4. "net"
    5. )
    6. // 0: invalid ip
    7. // 4: IPv4
    8. // 6: IPv6
    9. func ParseIP(s string) (net.IP, int) {
    10. ip := net.ParseIP(s)
    11. if ip == nil {
    12. return nil, 0
    13. }
    14. for i := 0; i < len(s); i++ {
    15. switch s[i] {
    16. case '.':
    17. return ip, 4
    18. case ':':
    19. return ip, 6
    20. }
    21. }
    22. return nil, 0
    23. }
    24. func test(s string) {
    25. ip, n := ParseIP(s)
    26. fmt.Printf("%v %v\n", n, ip)
    27. }
    28. func main() {
    29. test("127.0.0.1")
    30. test("::127.0.0.1")
    31. test("2001:0:53ab:0:0:0:0:0")
    32. test("2001:0:c38c:ffff:ffff:0000:0000:ffff")
    33. test("2001:0:c38c:ffff:ffff::")
    34. test("327.0.0.1")
    35. test("2001:0:c38c:ffff:ffff:ffff:ffff:ffff1")
    36. }
    1. 4 127.0.0.1
    2. 6 ::7f00:1
    3. 6 2001:0:53ab::
    4. 6 2001:0:c38c:ffff:ffff::ffff
    5. 6 2001:0:c38c:ffff:ffff::
    6. 0 <nil>
    7. 0 <nil>