Skip to content
Snippets Groups Projects
Commit 499c01a7 authored by wuyingfengsui's avatar wuyingfengsui
Browse files

new_with_specific_source

parent 9b3c4674
No related branches found
No related tags found
No related merge requests found
...@@ -18,32 +18,36 @@ pub struct CoAPClient { ...@@ -18,32 +18,36 @@ pub struct CoAPClient {
} }
impl CoAPClient { impl CoAPClient {
/// Create a CoAP client with the peer address. /// Create a CoAP client with the specific source and peer address.
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<CoAPClient> { pub fn new_with_specific_source<A: ToSocketAddrs, B: ToSocketAddrs>(bind_addr: A, peer_addr: B) -> Result<CoAPClient> {
addr.to_socket_addrs().and_then(|mut iter| { peer_addr.to_socket_addrs().and_then(|mut iter| {
match iter.next() { match iter.next() {
Some(SocketAddr::V4(a)) => { Some(paddr) => {
UdpSocket::bind("0.0.0.0:0").and_then(|s| { UdpSocket::bind(bind_addr).and_then(|s| {
s.set_read_timeout(Some(Duration::new(DEFAULT_RECEIVE_TIMEOUT, 0))) s.set_read_timeout(Some(Duration::new(DEFAULT_RECEIVE_TIMEOUT, 0)))
.and_then(|_| { .and_then(|_| {
Ok(CoAPClient { Ok(CoAPClient {
socket: s, socket: s,
peer_addr: SocketAddr::V4(a), peer_addr: paddr,
}) })
}) })
}) })
} }
Some(SocketAddr::V6(a)) => { None => Err(Error::new(ErrorKind::Other, "no address")),
UdpSocket::bind(":::0").and_then(|s| { }
s.set_read_timeout(Some(Duration::new(DEFAULT_RECEIVE_TIMEOUT, 0)))
.and_then(|_| {
Ok(CoAPClient {
socket: s,
peer_addr: SocketAddr::V6(a),
})
})
}) })
} }
/// Create a CoAP client with the peer address.
pub fn new<A: ToSocketAddrs>(addr: A) -> Result<CoAPClient> {
addr.to_socket_addrs().and_then(|mut iter| {
match iter.next() {
Some(SocketAddr::V4(_)) => {
Self::new_with_specific_source("0.0.0.0:0", addr)
}
Some(SocketAddr::V6(_)) => {
Self::new_with_specific_source(":::0", addr)
}
None => Err(Error::new(ErrorKind::Other, "no address")), None => Err(Error::new(ErrorKind::Other, "no address")),
} }
}) })
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment