Skip to content

Commit 9a1cfbe

Browse files
authored
net/server/listen-unused: simpler and with IPv6 support. (#690)
Uses ToSocketAddrs' trait to have any of IPv4 or IPv6 as supported by the OS, or even DNS names.
1 parent 857f2d4 commit 9a1cfbe

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

src/net/server/listen-unused.md

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,15 @@
33
[![std-badge]][std] [![cat-net-badge]][cat-net]
44

55
In this example, the port is displayed on the console, and the program will
6-
listen until a request is made. `SocketAddrV4` assigns a random port when
7-
setting port to 0.
6+
listen until a request is made. `TcpListener::bind` uses a random port
7+
allocated by the OS when requested to bind to port 0.
88

99
```rust,edition2018,no_run
10-
use std::net::{SocketAddrV4, Ipv4Addr, TcpListener};
10+
use std::net::TcpListener;
1111
use std::io::{Read, Error};
1212
1313
fn main() -> Result<(), Error> {
14-
let loopback = Ipv4Addr::new(127, 0, 0, 1);
15-
let socket = SocketAddrV4::new(loopback, 0);
16-
let listener = TcpListener::bind(socket)?;
14+
let listener = TcpListener::bind("localhost:0")?;
1715
let port = listener.local_addr()?;
1816
println!("Listening on {}, access this port to end the program", port);
1917
let (mut tcp_stream, addr) = listener.accept()?; //block until requested

0 commit comments

Comments
 (0)