在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 如果是有效的 IPv4 地址,返回 "IPv4" ; 示例 1: package main import ( "fmt" "strings" "strconv" ) func main() { //a := 0 //fmt.Scan(&a) //fmt.Printf("%d\n", a) s := "1e1.4.5.6" case1 := "2001:0db8:85a3:0:0:8A2E:0370:7334" case2 := "2001:0db8:85a3:0:0:8A2E:0370:7334:" res := IsIpv4OrIpv6(s) fmt.Println(res) res1 := IsIpv4OrIpv6(case1) fmt.Println(res1) res2 := IsIpv4OrIpv6(case2) fmt.Println(res2) fmt.Printf("Hello World!\n"); } func IsIpv4OrIpv6(ip string) string{ if len(ip)<7 { return "Neither" } arrIpv4 := strings.Split(ip,".") if len(arrIpv4) == 4{ //. 判断IPv4 for _,val := range arrIpv4{ if !Judgev4(val){ return "Neither" } } return "IPv4" } arrIpv6 := strings.Split(ip,":") if len(arrIpv6) == 8{ // 判断Ipv6 for _,val := range arrIpv6{ if !Judgev6(val){ return "Neither" } } return "IPv6" } return "Neither" } func Judgev4(ips string) bool{ if len(ips) >3{ return false } nums ,err := strconv.Atoi(ips) if err!= nil { return false } if nums <0 || nums>255{ return false } if len(ips)>1 && ips[0] == '0'{ return false } return true } func Judgev6(ips string) bool{ if ips == ""{ return true } if len(ips) >4{ return false } for _,val := range ips{ if !((val>='0'&&val<='9')||(val >='a' &&val <= 'f')||(val >= 'A'&&val<='F')){ return false } } return true }
|
请发表评论