1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::io::Result as IoResult;
use std::net::UdpSocket;

pub mod cmd;

#[derive(Debug)]
pub struct Ip {
    pub local: String,
    pub network: String,
}

#[derive(Debug)]
pub struct Host {
    pub ip: String,
    pub port: String,
}

impl Host {
    pub fn get(self) -> String {
        format!("{}:{}", self.ip, self.port)
    }
}

pub fn ifconfig() -> IoResult<Ip> {
    Ok(cmd::exec::ifconfig().unwrap())
}

pub fn network() -> Option<Host> {
    let network = ifconfig().unwrap().network;
    let host = format!("{}:{}", network, 0);
    let socket = UdpSocket::bind(host).unwrap();
    Some(Host{
        ip: socket.local_addr().unwrap().ip().to_string(),
        port: socket.local_addr().unwrap().port().to_string(),
    })
}

pub fn local() -> Option<Host> {
    let local = ifconfig().unwrap().local;
    let host = format!("{}:{}", local, 0);
    let socket = UdpSocket::bind(host).unwrap();
    Some(Host{
        ip: socket.local_addr().unwrap().ip().to_string(),
        port: socket.local_addr().unwrap().port().to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ifconfig() {
        assert!(ifconfig().is_ok());
    }

    #[test]
    fn test_network() {
        assert!(network().is_some())
    }

    #[test]
    fn test_local() {
        assert!(local().is_some())
    }
}