- Go 版本
func getLocalIP() (ip string, err error) {
ip = "127.0.0.1"
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return
}
defer conn.Close()
ip = conn.LocalAddr().(*net.UDPAddr).IP.String()
return
}
- Python 版本
def get_local_ip() -> str:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
try:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except OSError:
return "127.0.0.1"
网友评论