Rollup merge of #111527 - knickish:bind_port_0_documentation, r=Mark-Simulacrum

add examples of port 0 binding behavior

Was trying to find the method to specify the IP address but not the port, and there wasn't information easily accessible about it in the `TcpListener` or `SocketAddr`. Adding examples to `TcpListener` and `UdpSocket` for clarity.
This commit is contained in:
Dylan DPC 2023-05-18 10:52:34 +05:30 committed by GitHub
commit f9bbd23adf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 0 deletions

View File

@ -756,6 +756,15 @@ impl TcpListener {
/// ];
/// let listener = TcpListener::bind(&addrs[..]).unwrap();
/// ```
///
/// Creates a TCP listener bound to a port assigned by the operating system
/// at `127.0.0.1`.
///
/// ```no_run
/// use std::net::TcpListener;
///
/// let socket = TcpListener::bind("127.0.0.1:0").unwrap();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)

View File

@ -90,6 +90,15 @@ impl UdpSocket {
/// ];
/// let socket = UdpSocket::bind(&addrs[..]).expect("couldn't bind to address");
/// ```
///
/// Creates a UDP socket bound to a port assigned by the operating system
/// at `127.0.0.1`.
///
/// ```no_run
/// use std::net::UdpSocket;
///
/// let socket = UdpSocket::bind("127.0.0.1:0").unwrap();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<UdpSocket> {
super::each_addr(addr, net_imp::UdpSocket::bind).map(UdpSocket)