Go语言:判断IP是否合法是IPv4还是IPv6

原文链接:https://www.codenong.com/cs106100823/

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>

  

 

posted @ 2020-12-10 19:44  salami_china  阅读(1330)  评论(0编辑  收藏  举报