pu369com

rust 显示本机ip

显示本机ip

//#![windows_subsystem = "windows"] //运行时不显示cmd命令行窗口
use std::net::UdpSocket;
fn main() {    
  println!("{:?}",what_is_my_ip());
}
pub fn what_is_my_ip() -> Option<String> {
    let socket = match UdpSocket::bind("0.0.0.0:0") {
        Ok(s) => s,
        Err(_) => return None,
    };

    match socket.connect("8.8.8.8:80") {
        Ok(()) => (),
        Err(_) => return None,
    };

    match socket.local_addr() {
        Ok(addr) => return Some(addr.ip().to_string()),
        Err(_) => return None,
    };
}

 

参考:https://www.cnblogs.com/egmkang/p/11450741.html

posted on 2021-10-09 15:48  pu369com  阅读(158)  评论(0编辑  收藏  举报

导航