baidu

rust下获取本机IP

又拾起了rust语言, 想写一点东西玩一玩, 但是发现连一个获取本机IP地址的库都没有, 还得挽起袖子自己撸.

https://crates.io/crates/local_ipaddress

没有用ifconfig, 也没有扫描网卡, 就开了一个UdpSocket尝试着去连一个IP地址, 然后看本机IP是啥

 1 use std::net::UdpSocket;
 2 
 3 
 4 pub fn get() -> Option<String> {
 5     let socket = match UdpSocket::bind("0.0.0.0:0") {
 6         Ok(s) => s,
 7         Err(_) => return None,
 8     };
 9 
10     match socket.connect("8.8.8.8:80") {
11         Ok(()) => (),
12         Err(_) => return None,
13     };
14 
15     match socket.local_addr() {
16         Ok(addr) => return Some(addr.ip().to_string()),
17         Err(_) => return None,
18     };
19 }

 

这是使用的例子

use local_ipaddress;

fn main() {
    println!("{}", local_ipaddress::get().unwrap());
}

 

千万不要去用哪个local-ip, 或者machine ip之类的, 一个是通过ifconfig的返回获取IP地址的, 一个是扫描网卡, 在windows下都会panic

posted @ 2019-09-03 01:13  egmkang  阅读(3104)  评论(3编辑  收藏  举报