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

net/server/listen-unused: simpler and with IPv6 support. #690

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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: 4 additions & 6 deletions src/net/server/listen-unused.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,15 @@
[![std-badge]][std] [![cat-net-badge]][cat-net]

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

```rust,edition2018,no_run
use std::net::{SocketAddrV4, Ipv4Addr, TcpListener};
use std::net::TcpListener;
use std::io::{Read, Error};

fn main() -> Result<(), Error> {
let loopback = Ipv4Addr::new(127, 0, 0, 1);
let socket = SocketAddrV4::new(loopback, 0);
let listener = TcpListener::bind(socket)?;
let listener = TcpListener::bind("localhost:0")?;
let port = listener.local_addr()?;
println!("Listening on {}, access this port to end the program", port);
let (mut tcp_stream, addr) = listener.accept()?; //block until requested
Expand Down