0
点赞
收藏
分享

微信扫一扫

Go 获取本机网卡所有IP



阅读目录

  • Go 获取本机网卡所有IP
  • 提取字符串中"D999"后面的IP地址


Go 获取本机网卡所有IP

package main

import (
	"fmt"
	"net"
)

func main() {
	interfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println("Failed to get network interfaces:", err)
		return
	}

	for _, iface := range interfaces {
		addrs, err := iface.Addrs()
		if err != nil {
			fmt.Println("Failed to get addresses for interface", iface.Name, ":", err)
			continue
		}

		for _, addr := range addrs {
			ipNet, ok := addr.(*net.IPNet)
			if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
				fmt.Println("Interface:", iface.Name)
				fmt.Println("IP Address:", ipNet.IP)
			}
		}
	}
}

PS E:\TEXT\test> go run .\gogo.go
Interface: 本地连接
IP Address: 169.254.254.222
Interface: Mirage        
IP Address: 169.254.24.43
Interface: 以太网       
IP Address: 172.16.7.170
Interface: VirtualBox Host-Only Network
IP Address: 192.168.56.1
Interface: WLAN
IP Address: 169.254.135.251
Interface: 本地连接* 9    
IP Address: 169.254.23.217
Interface: 本地连接* 10
IP Address: 169.254.22.148
Interface: VMware Network Adapter VMnet1
IP Address: 192.168.149.1
Interface: VMware Network Adapter VMnet2
IP Address: 192.168.235.1
Interface: 以太网 2
IP Address: 169.254.151.85
Interface: vEthernet (WSL)
IP Address: 172.28.0.1
PS E:\TEXT\test>

提取字符串中"D999"后面的IP地址

package main

import (
	"fmt"
	"regexp"
)

func main() {
	str := "[通讯兵] 收到网络图: netmap: self: [21162] auth=machine-authorized u=? debug={\"DisableLogTail\":true} [100.64.1.70/32] [Hv9Py] d:59be947163c3243a D999 100.64.1.7      :   222.168.43.66:36941   172.16.22.148:60755   172.16.22.150:60755      172.17.0.1:60755      172.19.0.1:60755   192.168.1.110:60755"

	re := regexp.MustCompile(`D999\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
	match := re.FindStringSubmatch(str)
	if len(match) >= 2 {
		ip := match[1]
		fmt.Println("提取到的IP地址:", ip)
	} else {
		fmt.Println("未找到匹配的IP地址")
	}
}

PS E:\TEXT\test> go run .\gogo.go
提取到的IP地址: 100.64.1.7
PS E:\TEXT\test>

正则表达式 D999\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) 用于匹配以"D999"开头,后面跟着一个或多个空格,并且紧跟着一个IP地址的字符串。

(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) 用于匹配IP地址的部分,其中 \d{1,3} 表示一个由 1 到 3 位数字组成的部分,\. 用于匹配点号分隔符。


举报

相关推荐

0 条评论