package mainimport ("fmt""net""regexp"
)func Ipv6PatternStr(data string) []net.IP {var ips []net.IP// 使用正则表达式匹配以240开头,可能包含::的IPv6地址部分// 注意:这个正则表达式不会确保整个IPv6地址的合法性,只是匹配部分字符串ipv6Pattern := `240[0-9a-fA-F]+(:[0-9a-fA-F]+)*(::([0-9a-fA-F]+:)*[0-9a-fA-F]+)?`re := regexp.MustCompile(ipv6Pattern)// 查找所有匹配的IPv6地址部分matches := re.FindAllString(data, -1)// 输出结果for _, match := range matches {ip := net.ParseIP(match)if ip != nil {ips = append(ips, ip)}}return ips
}
func main() {// 假设这是从某个源获取的数据字符串data := `eth0@if31: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000 inet6 240e:350:8947:c401::3bf/128 scope global dynamic noprefixroute valid_lft 2729sec preferred_lft 2729sec inet6 240e:350:8947:c401:8c92:99ff:fe1f:eaaf/64 scope global dynamic mngtmpaddr noprefixroute valid_lft 2728sec preferred_lft 2728sec inet6 fe80::8c92:99ff:fe1f:eacf/64 scope link valid_lft forever preferred_lft forever`ips := Ipv6PatternStr(data)if len(ips) == 0 {fmt.Println("No IPv6 address found")return}fmt.Println("IPv6 addresses found:")for _, ip := range ips {fmt.Println(ip)}
}
效果如下
PS C:\Users\Y\GolandProjects\tt> go run .\main.go
IPv6 addresses found:
240e:350:8947:c401::3bf
240e:350:8947:c401:8c92:99ff:fe1f:eaaf
PS C:\Users\Y\GolandProjects\tt>