package main
import (
"fmt"
"net"
)
// 0: invalid ip
// 4: IPv4
// 6: IPv6
func ParseIP(s string) (net.IP, int) {
ip := net.ParseIP(s)
if ip == nil {
return nil, 0
}
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return ip, 4
case ':':
return ip, 6
}
}
return nil, 0
}
func test(s string) {
ip, n := ParseIP(s)
fmt.Printf("%v %v\n", n, ip)
}
func main() {
test("127.0.0.1")
test("::127.0.0.1")
test("2001:0:53ab:0:0:0:0:0")
test("2001:0:c38c:ffff:ffff:0000:0000:ffff")
test("2001:0:c38c:ffff:ffff::")
test("327.0.0.1")
test("2001:0:c38c:ffff:ffff:ffff:ffff:ffff1")
}
4 127.0.0.1
6 ::7f00:1
6 2001:0:53ab::
6 2001:0:c38c:ffff:ffff::ffff
6 2001:0:c38c:ffff:ffff::
0 <nil>
0 <nil>