A network or local socket
This is a low-level socket type that provides direct access to socket options. For most use cases, prefer TcpStream, TcpListener, or UdpSocket.
Use Socket when you need to configure socket options before binding or connecting,
such as setting SO_REUSEADDR or SO_REUSEPORT.
Example
use std::net::Socket;
// Create a TCP socket and configure it before binding
let sock = Socket::new(libc::AF_INET6, libc::SOCK_STREAM).unwrap();
defer sock.close();
sock.set_reuse_address(true).unwrap();
sock.set_reuse_port(true).unwrap();
// Now you can use the socket with low-level bind/listen/connect calls
// or convert it to TcpListener/TcpStream/UdpSocket using from_socket()
Run this example
Fields
-
fd: FileDescriptor
Methods
impl Socket { ... }
-
Create a new socket with a given family and type
-
fn as_fd(self: &Socket) -> FileDescriptor
-
Shuts down the reading or writing end of the socket or both.
-
Sets the value of the
SO_REUSEADDRoption for this socket.This option allows the socket to bind to an address that is in the TIME_WAIT state, which is useful when restarting a server to avoid "address already in use" errors.
-
Sets the value of the
SO_REUSEPORToption for this socket.This option allows multiple sockets to bind to the same address and port, enabling load balancing of incoming connections across multiple processes or threads.
-
fn recv_from_with_flags(self: &Socket, buf: &mut [u8], flags: c_int) -> Result<(usize, SocketAddr)>
-
-
Reads from the stream into a provided buffer.
If successful, returns the number of bytes read. This may be less than the size of the provided buffer.
-
fn peer_addr(self: &Socket) -> Result<SocketAddr>
Returns the address of the remote peer
-
fn socket_addr(self: &Socket) -> Result<SocketAddr>
Returns the address of the remote peer
-
Closes the socket.
Mixins
impl Socket { ... }
-
mixin FdReadWrite<Socket>
-
Write the buffer to the stream.
Returns the number of bytes written. This may be less than the size of the buffer. See also write_all, which can be used to write the entire buffer.