获取本机 IP 地址

  1. 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
}
  1. 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"

你可能感兴趣的:(获取本机 IP 地址)