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
use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
use std::str;
use std::time::Duration;
use common::{messages, parsing};
use errors::SearchError;
use gateway::Gateway;
pub fn search_gateway() -> Result<Gateway, SearchError> {
search_gateway_timeout(Duration::from_secs(3))
}
pub fn search_gateway_timeout(timeout: Duration) -> Result<Gateway, SearchError> {
search_gateway_from_timeout(Ipv4Addr::new(0, 0, 0, 0), timeout)
}
pub fn search_gateway_from(ip: Ipv4Addr) -> Result<Gateway, SearchError> {
search_gateway_from_timeout(ip, Duration::from_secs(3))
}
pub fn search_gateway_from_timeout(ip: Ipv4Addr, timeout: Duration) -> Result<Gateway, SearchError> {
let addr = SocketAddrV4::new(ip, 0);
let socket = try!(UdpSocket::bind(addr));
try!(socket.set_read_timeout(Some(timeout)));
try!(socket.send_to(messages::SEARCH_REQUEST.as_bytes(), "239.255.255.250:1900",));
loop {
let mut buf = [0u8; 1024];
let (read, _) = try!(socket.recv_from(&mut buf));
let text = try!(str::from_utf8(&buf[..read]));
let location = parsing::parse_search_result(text)?;
if let Ok(control_url) = get_control_url(&location) {
return Ok(Gateway {
addr: location.0,
control_url: control_url,
});
}
}
}
fn get_control_url(location: &(SocketAddrV4, String)) -> Result<String, SearchError> {
let url = format!("http://{}:{}{}", location.0.ip(), location.0.port(), location.1);
let (_, _, body) = lynx::Request::get(&url).send()?;
parsing::parse_control_url(&body.bytes()?[..])
}