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>

  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM