Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add bind_reusablemethod to UdpSocket #21480

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/libstd/io/net/udp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,16 @@ impl UdpSocket {
})
}

/// Creates a UDP socket from the given address with `SO_REUSEADDR` set to true.
///
/// Address type can be any implementor of `ToSocketAddr` trait. See its
/// documentation for concrete examples.
pub fn bind_reusable<A: ToSocketAddr>(addr: A) -> IoResult<UdpSocket> {
super::with_addresses(addr, |addr| {
UdpSocketImp::bind_reusable(addr).map(|s| UdpSocket { inner: s })
})
}

/// Receives data from the socket. On success, returns the number of bytes
/// read and the address from whence the data came.
pub fn recv_from(&mut self, buf: &mut [u8]) -> IoResult<(uint, SocketAddr)> {
Expand Down
22 changes: 22 additions & 0 deletions src/libstd/sys/common/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,28 @@ impl UdpSocket {
}
}

pub fn bind_reusable(addr: SocketAddr) -> IoResult<UdpSocket> {
sys::init_net();

let fd = try!(socket(addr, libc::SOCK_DGRAM));
let ret = UdpSocket {
inner: Arc::new(Inner::new(fd)),
read_deadline: 0,
write_deadline: 0,
};

setsockopt(fd, libc::SOL_SOCKET, libc::SO_REUSEADDR, true as libc::c_int).unwrap();

let mut storage = unsafe { mem::zeroed() };
let len = addr_to_sockaddr(addr, &mut storage);
let addrp = &storage as *const _ as *const libc::sockaddr;

match unsafe { libc::bind(fd, addrp, len) } {
-1 => Err(last_error()),
_ => Ok(ret),
}
}

pub fn fd(&self) -> sock_t { self.inner.fd }

pub fn set_broadcast(&mut self, on: bool) -> IoResult<()> {
Expand Down