pub struct TcpListener(/* private fields */);Expand description
A TCP socket server, listening for connections.
After creating aTcpListener bybinding it to a socket address, it listensfor incoming TCP connections. These can be accepted by callingaccept or byiterating over theIncoming iterator returned byincoming.
The socket will be closed when the value is dropped.
The Transmission Control Protocol is specified inIETF RFC 793.
§Examples
Implementations§
Source§implTcpListener
implTcpListener
1.0.0 ·Sourcepub fnbind<A:ToSocketAddrs>(addr: A) ->Result<TcpListener>
pub fnbind<A:ToSocketAddrs>(addr: A) ->Result<TcpListener>
Creates a newTcpListener which will be bound to the specifiedaddress.
The returned listener is ready for accepting connections.
Binding with a port number of 0 will request that the OS assigns a portto this listener. The port allocated can be queried via theTcpListener::local_addr method.
The address type can be any implementor ofToSocketAddrs trait. Seeits documentation for concrete examples.
Ifaddr yields multiple addresses,bind will be attempted witheach of the addresses until one succeeds and returns the listener. Ifnone of the addresses succeed in creating a listener, the error returnedfrom the last attempt (the last address) is returned.
§Examples
Creates a TCP listener bound to127.0.0.1:80:
Creates a TCP listener bound to127.0.0.1:80. If that fails, create aTCP listener bound to127.0.0.1:443:
usestd::net::{SocketAddr, TcpListener};letaddrs = [ SocketAddr::from(([127,0,0,1],80)), SocketAddr::from(([127,0,0,1],443)),];letlistener = TcpListener::bind(&addrs[..]).unwrap();Creates a TCP listener bound to a port assigned by the operating systemat127.0.0.1.
1.0.0 ·Sourcepub fnlocal_addr(&self) ->Result<SocketAddr>
pub fnlocal_addr(&self) ->Result<SocketAddr>
Returns the local socket address of this listener.
§Examples
1.0.0 ·Sourcepub fntry_clone(&self) ->Result<TcpListener>
pub fntry_clone(&self) ->Result<TcpListener>
Creates a new independently owned handle to the underlying socket.
The returnedTcpListener is a reference to the same socket that thisobject references. Both handles can be used to accept incomingconnections and options set on one listener will affect the other.
§Examples
1.0.0 ·Sourcepub fnaccept(&self) ->Result<(TcpStream,SocketAddr)>
pub fnaccept(&self) ->Result<(TcpStream,SocketAddr)>
1.0.0 ·Sourcepub fnincoming(&self) ->Incoming<'_>ⓘ
pub fnincoming(&self) ->Incoming<'_>ⓘ
Returns an iterator over the connections being received on thislistener.
The returned iterator will never returnNone and will also not yieldthe peer’sSocketAddr structure. Iterating over it is equivalent tocallingTcpListener::accept in a loop.
§Examples
usestd::net::{TcpListener, TcpStream};fnhandle_connection(stream: TcpStream) {//...}fnmain() -> std::io::Result<()> {letlistener = TcpListener::bind("127.0.0.1:80")?;forstreaminlistener.incoming() {matchstream {Ok(stream) => { handle_connection(stream); }Err(e) => {/* connection failed */} } }Ok(())}Sourcepub fninto_incoming(self) ->IntoIncomingⓘ
🔬This is a nightly-only experimental API. (tcplistener_into_incoming #88373)
pub fninto_incoming(self) ->IntoIncomingⓘ
tcplistener_into_incoming #88373)Turn this into an iterator over the connections being received on thislistener.
The returned iterator will never returnNone and will also not yieldthe peer’sSocketAddr structure. Iterating over it is equivalent tocallingTcpListener::accept in a loop.
§Examples
#![feature(tcplistener_into_incoming)]usestd::net::{TcpListener, TcpStream};fnlisten_on(port: u16) ->implIterator<Item = TcpStream> {letlistener = TcpListener::bind(("127.0.0.1", port)).unwrap(); listener.into_incoming() .filter_map(Result::ok)/* Ignore failed connections */}fnmain() -> std::io::Result<()> {forstreaminlisten_on(80) {/* handle the connection here */}Ok(())}1.9.0 ·Sourcepub fnset_ttl(&self, ttl:u32) ->Result<()>
pub fnset_ttl(&self, ttl:u32) ->Result<()>
Sets the value for theIP_TTL option on this socket.
This value sets the time-to-live field that is used in every packet sentfrom this socket.
§Examples
1.9.0 ·Sourcepub fnttl(&self) ->Result<u32>
pub fnttl(&self) ->Result<u32>
Gets the value of theIP_TTL option for this socket.
For more information about this option, seeTcpListener::set_ttl.
§Examples
pub fnset_only_v6(&self, only_v6:bool) ->Result<()>
pub fnonly_v6(&self) ->Result<bool>
1.9.0 ·Sourcepub fntake_error(&self) ->Result<Option<Error>>
pub fntake_error(&self) ->Result<Option<Error>>
Gets the value of theSO_ERROR option on this socket.
This will retrieve the stored error in the underlying socket, clearingthe field in the process. This can be useful for checking errors betweencalls.
§Examples
1.9.0 ·Sourcepub fnset_nonblocking(&self, nonblocking:bool) ->Result<()>
pub fnset_nonblocking(&self, nonblocking:bool) ->Result<()>
Moves this TCP stream into or out of nonblocking mode.
This will result in theaccept operation becoming nonblocking,i.e., immediately returning from their calls. If the IO operation issuccessful,Ok is returned and no further action is required. If theIO operation could not be completed and needs to be retried, an errorwith kindio::ErrorKind::WouldBlock is returned.
On Unix platforms, calling this method corresponds to callingfcntlFIONBIO. On Windows calling this method corresponds to callingioctlsocketFIONBIO.
§Examples
Bind a TCP listener to an address, listen for connections, and readbytes in nonblocking mode:
usestd::io;usestd::net::TcpListener;letlistener = TcpListener::bind("127.0.0.1:7878").unwrap();listener.set_nonblocking(true).expect("Cannot set non-blocking");forstreaminlistener.incoming() {matchstream {Ok(s) => {// do something with the TcpStreamhandle_connection(s); }Err(refe)ife.kind() == io::ErrorKind::WouldBlock => {// wait until network socket is ready, typically implemented // via platform-specific APIs such as epoll or IOCPwait_for_fd();continue; }Err(e) =>panic!("encountered IO error: {e}"), }}Trait Implementations§
1.63.0 ·Source§implAsFd forTcpListener
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implAsFd forTcpListener
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.Source§fnas_fd(&self) ->BorrowedFd<'_>
fnas_fd(&self) ->BorrowedFd<'_>
1.0.0 ·Source§implAsRawFd forTcpListener
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implAsRawFd forTcpListener
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.1.0.0 ·Source§implAsRawSocket forTcpListener
Available onWindows only.
implAsRawSocket forTcpListener
Source§fnas_raw_socket(&self) ->RawSocket
fnas_raw_socket(&self) ->RawSocket
1.63.0 ·Source§implAsSocket forTcpListener
Available onWindows only.
implAsSocket forTcpListener
Source§fnas_socket(&self) ->BorrowedSocket<'_>
fnas_socket(&self) ->BorrowedSocket<'_>
1.0.0 ·Source§implDebug forTcpListener
implDebug forTcpListener
1.63.0 ·Source§implFrom<OwnedFd> forTcpListener
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implFrom<OwnedFd> forTcpListener
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.1.63.0 ·Source§implFrom<OwnedSocket> forTcpListener
Available onWindows only.
implFrom<OwnedSocket> forTcpListener
Source§fnfrom(owned:OwnedSocket) -> Self
fnfrom(owned:OwnedSocket) -> Self
1.63.0 ·Source§implFrom<TcpListener> forOwnedFd
Available on(Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.
implFrom<TcpListener> forOwnedFd
target_os=trusty or WASI ortarget_os=motor) and non-target_os=trusty only.Source§fnfrom(tcp_listener:TcpListener) ->OwnedFd
fnfrom(tcp_listener:TcpListener) ->OwnedFd
Takes ownership of aTcpListener’s socket file descriptor.
1.63.0 ·Source§implFrom<TcpListener> forOwnedSocket
Available onWindows only.
implFrom<TcpListener> forOwnedSocket
Source§fnfrom(tcp_listener:TcpListener) ->OwnedSocket
fnfrom(tcp_listener:TcpListener) ->OwnedSocket
Takes ownership of aTcpListener’s socket.
1.1.0 ·Source§implFromRawFd forTcpListener
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implFromRawFd forTcpListener
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.Source§unsafe fnfrom_raw_fd(fd:RawFd) ->TcpListener
unsafe fnfrom_raw_fd(fd:RawFd) ->TcpListener
Self from the given raw filedescriptor.Read more1.1.0 ·Source§implFromRawSocket forTcpListener
Available onWindows only.
implFromRawSocket forTcpListener
Source§unsafe fnfrom_raw_socket(sock:RawSocket) ->TcpListener
unsafe fnfrom_raw_socket(sock:RawSocket) ->TcpListener
1.4.0 ·Source§implIntoRawFd forTcpListener
Available onnon-target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.
implIntoRawFd forTcpListener
target_os=trusty and (Unix or HermitCore ortarget_os=trusty or WASI ortarget_os=motor) only.