info > socket(7)

🏷️ NAME

socket - Linux socket interface

🚀 Quick Reference

Use Case Command Description
Create a socket socket(int family, int type, int protocol) 📦 Creates an endpoint for communication.
Bind to address bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) 🔗 Assigns a name to a socket.
Listen for connections listen(int sockfd, int backlog) 👂 Marks socket as passive to accept incoming connections.
Accept a connection accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) 🤝 Accepts a new connection on a listening socket.
Connect to remote connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) 🔌 Initiates a connection to a remote socket.
Send data send(int sockfd, const void *buf, size_t len, int flags) 📤 Send data over a socket.
Receive data recv(int sockfd, void *buf, size_t len, int flags) 📥 Receive data from a socket.
Set socket option setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen) ⚙️ Set options on a socket (e.g., SO_REUSEADDR).
Get socket option getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) 🔍 Retrieve current socket options.
Close a socket close(int sockfd) ❌ Closes a socket file descriptor.
Non-blocking I/O fcntl(sockfd, F_SETFL, O_NONBLOCK) ⏩ Set socket to non-blocking mode.
Multiplex I/O poll(struct pollfd *fds, nfds_t nfds, int timeout);
select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
⏱️ Wait for events on multiple sockets.
Get local address getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen) 🏠 Retrieve the local address of a socket.
Get peer address getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) 👥 Retrieve the remote address connected to this socket.
Shutdown socket shutdown(int sockfd, int how) 🚫 Shut down part of a full-duplex connection.
Attach BPF filter (Linux) setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog)) 🛡️ Attach a packet filter to a socket.
Perl: Use Socket module use Socket qw(:DEFAULT :addrinfo); 📦 Import socket constants and functions.
Perl: Resolve hostname to address my ($err, @res) = getaddrinfo($host, $service, \%hints); 🌐 Convert hostname/service to address structures.
Perl: Address to hostname my ($err, $host, $serv) = getnameinfo($sockaddr, $flags); 🔁 Convert socket address to human-readable strings.
Perl: Pack socket address (IPv4) my $sockaddr = pack_sockaddr_in($port, $ip_address); 📦 Pack port and IP into sockaddr_in structure.
Perl: Unpack socket address (IPv4) my ($port, $ip) = unpack_sockaddr_in($sockaddr); 📦 Extract port and IP from sockaddr_in.
Perl: Pack socket address (IPv6) my $sockaddr = pack_sockaddr_in6($port, $ip6_address, $scope_id, $flowinfo); 📦 Pack IPv6 address into sockaddr_in6.
Perl: Unpack socket address (IPv6) my ($port, $ip6, $scope, $flow) = unpack_sockaddr_in6($sockaddr); 📦 Extract IPv6 components from structure.
Perl: Pack Unix socket address my $sockaddr = pack_sockaddr_un($path); 📁 Pack pathname into sockaddr_un.

📖 SYNOPSIS

#include <sys/socket.h>

sockfd = socket(int socket_family, int socket_type, int protocol);

📝 DESCRIPTION

This manual page describes the Linux networking socket layer user interface. The BSD compatible sockets are the uniform interface between the user process and the network protocol stacks in the kernel. The protocol modules are grouped into protocol families such as AF_INET, AF_IPX, and AF_PACKET, and socket types such as SOCK_STREAM or SOCK_DGRAM. See socket(2) for more information on families and types.

🔧 Socket-layer functions

These functions are used by the user process to send or receive packets and to do other socket operations. For more information see their respective manual pages.

Seeking, or calling pread(2) or pwrite(2) with a nonzero position is not supported on sockets.

It is possible to do nonblocking I/O on sockets by setting the O_NONBLOCK flag on a socket file descriptor using fcntl(2). Then all operations that would block will (usually) return with EAGAIN (operation should be retried later); connect(2) will return EINPROGRESS error. The user can then wait for various events via poll(2) or select(2).

I/O events
Event Poll flag Occurrence
Read POLLIN 📥 New data arrived.
Read POLLIN 🔗 A connection setup has been completed (for connection-oriented sockets)
Read POLLHUP 🚫 A disconnection request has been initiated by the other end.
Read POLLHUP 💔 A connection is broken (only for connection-oriented protocols). When the socket is written SIGPIPE is also sent.
Write POLLOUT 📤 Socket has enough send buffer space for writing new data.
Read/Write POLLIN | POLLOUT ✅ An outgoing connect(2) finished.
Read/Write POLLERR ⚠️ An asynchronous error occurred.
Read/Write POLLHUP 🔚 The other end has shut down one direction.
Exception POLLPRI 🚨 Urgent data arrived. SIGURG is sent then.

An alternative to poll(2) and select(2) is to let the kernel inform the application about events via a SIGIO signal. For that the O_ASYNC flag must be set on a socket file descriptor via fcntl(2) and a valid signal handler for SIGIO must be installed via sigaction(2). See the Signals discussion below.

🏠 Socket address structures

Each socket domain has its own format for socket addresses, with a domain-specific address structure. Each of these structures begins with an integer "family" field (typed as sa_family_t) that indicates the type of the address structure. This allows the various system calls (e.g., connect(2), bind(2), accept(2), getsockname(2), getpeername(2)), which are generic to all socket domains, to determine the domain of a particular socket address.

To allow any type of socket address to be passed to interfaces in the sockets API, the type struct sockaddr is defined. The purpose of this type is purely to allow casting of domain-specific socket address types to a "generic" type, so as to avoid compiler warnings about type mismatches in calls to the sockets API.

In addition, the sockets API provides the data type struct sockaddr_storage. This type is suitable to accommodate all supported domain-specific socket address structures; it is large enough and is aligned properly. (In particular, it is large enough to hold IPv6 socket addresses.) The structure includes the following field, which can be used to identify the type of socket address actually stored in the structure:

sa_family_t ss_family;

The sockaddr_storage structure is useful in programs that must handle socket addresses in a generic way (e.g., programs that must deal with both IPv4 and IPv6 socket addresses).

⚙️ Socket options

The socket options listed below can be set by using setsockopt(2) and read with getsockopt(2) with the socket level set to SOL_SOCKET for all sockets. Unless otherwise noted, optval is a pointer to an int.

📡 Signals

When writing onto a connection-oriented socket that has been shut down (by the local or the remote end) SIGPIPE is sent to the writing process and EPIPE is returned. The signal is not sent when the write call specified the MSG_NOSIGNAL flag.

When requested with the FIOSETOWN fcntl(2) or SIOCSPGRP ioctl(2), SIGIO is sent when an I/O event occurs. It is possible to use poll(2) or select(2) in the signal handler to find out which socket the event occurred on. An alternative (in Linux 2.2) is to set a real-time signal using the F_SETSIG fcntl(2); the handler of the real time signal will be called with the file descriptor in the si_fd field of its siginfo_t. See fcntl(2) for more information.

Under some circumstances (e.g., multiple processes accessing a single socket), the condition that caused the SIGIO may have already disappeared when the process reacts to the signal. If this happens, the process should wait again because Linux will resend the signal later.

📁 /proc interfaces

The core socket networking parameters can be accessed via files in the directory /proc/sys/net/core/.

🔧 Ioctls

These operations can be accessed using ioctl(2):

error = ioctl(ip_socket, ioctl_type, &value_result);

📅 VERSIONS

SO_BINDTODEVICE was introduced in Linux 2.0.30. SO_PASSCRED is new in Linux 2.2. The /proc interfaces were introduced in Linux 2.2. SO_RCVTIMEO and SO_SNDTIMEO are supported since Linux 2.3.41. Earlier, timeouts were fixed to a protocol-specific setting, and could not be read or written.

📝 NOTES

Linux assumes that half of the send/receive buffer is used for internal kernel structures; thus the values in the corresponding /proc files are twice what can be observed on the wire.

Linux will allow port reuse only with the SO_REUSEADDR option when this option was set both in the previous program that performed a bind(2) to the port and in the program that wants to reuse the port. This differs from some implementations (e.g., FreeBSD) where only the later program needs to set the SO_REUSEADDR option. Typically this difference is invisible, since, for example, a server program is designed to always set this option.

📚 SEE ALSO

wireshark(1), bpf(2), connect(2), getsockopt(2), setsockopt(2), socket(2), pcap(3), address_families(7), capabilities(7), ddp(7), ip(7), ipv6(7), packet(7), tcp(7), udp(7), unix(7), tcpdump(8)

📜 COLOPHON

This page is part of release 5.10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at https://www.kernel.org/doc/man-pages/.


🏷️ NAME

"Socket" - networking constants and support functions

📖 SYNOPSIS

"Socket" a low-level module used by, among other things, the IO::Socket family of modules. The following examples demonstrate some low-level uses but a practical program would likely use the higher-level API provided by IO::Socket or similar instead.

use Socket qw(PF_INET SOCK_STREAM pack_sockaddr_in inet_aton);

socket(my $socket, PF_INET, SOCK_STREAM, 0)
    or die "socket: $!";

my $port = getservbyname "echo", "tcp";
connect($socket, pack_sockaddr_in($port, inet_aton("localhost")))
    or die "connect: $!";

print $socket "Hello, world!\n";
print <$socket>;

See also the "EXAMPLES" section.

📝 DESCRIPTION

This module provides a variety of constants, structure manipulators and other functions related to socket-based networking. The values and functions provided are useful when used in conjunction with Perl core functions such as socket(), setsockopt() and bind(). It also provides several other support functions, mostly for dealing with conversions of network addresses between human-readable and native binary forms, and for hostname resolver operations.

Some constants and functions are exported by default by this module; but for backward-compatibility any recently-added symbols are not exported by default and must be requested explicitly. When an import list is provided to the use Socket line, the default exports are not automatically imported. It is therefore best practice to always to explicitly list all the symbols required.

Also, some common socket "newline" constants are provided: the constants CR, LF, and CRLF, as well as $CR, $LF, and $CRLF, which map to "\015", "\012", and "\015\012". If you do not want to use the literal characters in your programs, then use the constants provided here. They are not exported by default, but can be imported individually, and with the :crlf export tag:

use Socket qw(:DEFAULT :crlf);

$sock->print("GET / HTTP/1.0$CRLF");

The entire getaddrinfo() subsystem can be exported using the tag :addrinfo; this exports the getaddrinfo() and getnameinfo() functions, and all the AI_*, NI_*, NIx_* and EAI_* constants.

📦 CONSTANTS

In each of the following groups, there may be many more constants provided than just the ones given as examples in the section heading. If the heading ends "..." then this means there are likely more; the exact constants provided will depend on the OS and headers found at compile-time.

PF_INET, PF_INET6, PF_UNIX, ...

Protocol family constants to use as the first argument to socket() or the value of the SO_DOMAIN or SO_FAMILY socket option.

AF_INET, AF_INET6, AF_UNIX, ...

Address family constants used by the socket address structures, to pass to such functions as inet_pton() or getaddrinfo(), or are returned by such functions as sockaddr_family().

SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ...

Socket type constants to use as the second argument to socket(), or the value of the SO_TYPE socket option.

SOCK_NONBLOCK, SOCK_CLOEXEC

Linux-specific shortcuts to specify the O_NONBLOCK and FD_CLOEXEC flags during a socket(2) call.

socket( my $sockh, PF_INET, SOCK_DGRAM|SOCK_NONBLOCK, 0 )

SOL_SOCKET

Socket option level constant for setsockopt() and getsockopt().

SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ...

Socket option name constants for setsockopt() and getsockopt() at the SOL_SOCKET level.

IP_OPTIONS, IP_TOS, IP_TTL, ...

Socket option name constants for IPv4 socket options at the IPPROTO_IP level.

IP_PMTUDISC_WANT, IP_PMTUDISC_DONT, ...

Socket option value constants for IP_MTU_DISCOVER socket option.

IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ...

Socket option value constants for IP_TOS socket option.

MSG_BCAST, MSG_OOB, MSG_TRUNC, ...

Message flag constants for send() and recv().

SHUT_RD, SHUT_RDWR, SHUT_WR

Direction constants for shutdown().

INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE

Constants giving the special AF_INET addresses for wildcard, broadcast, local loopback, and invalid addresses. Normally equivalent to inet_aton('0.0.0.0'), inet_aton('255.255.255.255'), inet_aton('localhost') and inet_aton('255.255.255.255') respectively.

IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ...

IP protocol constants to use as the third argument to socket(), the level argument to getsockopt() or setsockopt(), or the value of the SO_PROTOCOL socket option.

TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ...

Socket option name constants for TCP socket options at the IPPROTO_TCP level.

IN6ADDR_ANY, IN6ADDR_LOOPBACK

Constants giving the special AF_INET6 addresses for wildcard and local loopback. Normally equivalent to inet_pton(AF_INET6, "::") and inet_pton(AF_INET6, "::1") respectively.

IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...

Socket option name constants for IPv6 socket options at the IPPROTO_IPV6 level.

🔧 STRUCTURE MANIPULATORS

The following functions convert between lists of Perl values and packed binary strings representing structures.

🔧 FUNCTIONS

getaddrinfo() / getnameinfo() ERROR CONSTANTS

The following constants may be returned by getaddrinfo() or getnameinfo(). Others may be provided by the OS.

📝 EXAMPLES

🔌 Lookup for connect()

The getaddrinfo() function converts a hostname and a service name into a list of structures, each containing a potential way to connect() to the named service on the named host.

use IO::Socket;
use Socket qw(SOCK_STREAM getaddrinfo);

my %hints = (socktype => SOCK_STREAM);
my ($err, @res) = getaddrinfo("localhost", "echo", \%hints);
die "Cannot getaddrinfo - $err" if $err;

my $sock;

foreach my $ai (@res) {
    my $candidate = IO::Socket->new();

    $candidate->socket($ai->{family}, $ai->{socktype}, $ai->{protocol})
        or next;

    $candidate->connect($ai->{addr})
        or next;

    $sock = $candidate;
    last;
}

die "Cannot connect to localhost:echo" unless $sock;

$sock->print("Hello, world!\n");
print <$sock>;

Because a list of potential candidates is returned, the "while" loop tries each in turn until it finds one that succeeds both the socket() and connect() calls. This function performs the work of the legacy functions gethostbyname(), getservbyname(), inet_aton() and pack_sockaddr_in(). In practice this logic is better performed by IO::Socket::IP.

🔍 Making a human-readable string out of an address

The getnameinfo() function converts a socket address, such as returned by getsockname() or getpeername(), into a pair of human-readable strings representing the address and service name.

use IO::Socket::IP;
use Socket qw(getnameinfo);

my $server = IO::Socket::IP->new(LocalPort => 12345, Listen => 1) or
    die "Cannot listen - $@";

my $socket = $server->accept or die "accept: $!";

my ($err, $hostname, $servicename) = getnameinfo($socket->peername);
die "Cannot getnameinfo - $err" if $err;

print "The peer is connected from $hostname\n";

Since in this example only the hostname was used, the redundant conversion of the port number into a service name may be omitted by passing the NIx_NOSERV flag.

use Socket qw(getnameinfo NIx_NOSERV);

my ($err, $hostname) = getnameinfo($socket->peername, 0, NIx_NOSERV);

This function performs the work of the legacy functions unpack_sockaddr_in(), inet_ntoa(), gethostbyaddr() and getservbyport(). In practice this logic is better performed by IO::Socket::IP.

🌐 Resolving hostnames into IP addresses

To turn a hostname into a human-readable plain IP address use getaddrinfo() to turn the hostname into a list of socket structures, then getnameinfo() on each one to make it a readable IP address again.

use Socket qw(:addrinfo SOCK_RAW);

my ($err, @res) = getaddrinfo($hostname, "", {socktype => SOCK_RAW});
die "Cannot getaddrinfo - $err" if $err;

while( my $ai = shift @res ) {
    my ($err, $ipaddr) = getnameinfo($ai->{addr}, NI_NUMERICHOST, NIx_NOSERV);
    die "Cannot getnameinfo - $err" if $err;

    print "$ipaddr\n";
}

The socktype hint to getaddrinfo() filters the results to only include one socket type and protocol. Without this most OSes return three combinations, for SOCK_STREAM, SOCK_DGRAM and SOCK_RAW, resulting in triplicate output of addresses. The NI_NUMERICHOST flag to getnameinfo() causes it to return a string-formatted plain IP address, rather than reverse resolving it back into a hostname. This combination performs the work of the legacy functions gethostbyname() and inet_ntoa().

⚙️ Accessing socket options

The many SO_* and other constants provide the socket option names for getsockopt() and setsockopt().

use IO::Socket::INET;
use Socket qw(SOL_SOCKET SO_RCVBUF IPPROTO_IP IP_TTL);

my $socket = IO::Socket::INET->new(LocalPort => 0, Proto => 'udp')
    or die "Cannot create socket: $@";

$socket->setsockopt(SOL_SOCKET, SO_RCVBUF, 64*1024) or
    die "setsockopt: $!";

print "Receive buffer is ", $socket->getsockopt(SOL_SOCKET, SO_RCVBUF),
    " bytes\n";

print "IP TTL is ", $socket->getsockopt(IPPROTO_IP, IP_TTL), "\n";

As a convenience, IO::Socket's setsockopt() method will convert a number into a packed byte buffer, and getsockopt() will unpack a byte buffer of the correct size back into a number.

✍️ AUTHOR

This module was originally maintained in Perl core by the Perl 5 Porters. It was extracted to dual-life on CPAN at version 1.95 by Paul Evans <leonerd@leonerd.uk>

socket(7)
🏷️ NAME 🚀 Quick Reference 📖 SYNOPSIS 📝 DESCRIPTION
🔧 Socket-layer functions 🏠 Socket address structures ⚙️ Socket options 📡 Signals 📁 /proc interfaces 🔧 Ioctls
📅 VERSIONS 📝 NOTES 📚 SEE ALSO 📜 COLOPHON 🏷️ NAME 📖 SYNOPSIS 📝 DESCRIPTION 📦 CONSTANTS
PF_INET, PF_INET6, PF_UNIX, ... AF_INET, AF_INET6, AF_UNIX, ... SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, ... SOCK_NONBLOCK, SOCK_CLOEXEC SOL_SOCKET SO_ACCEPTCONN, SO_BROADCAST, SO_ERROR, ... IP_OPTIONS, IP_TOS, IP_TTL, ... IP_PMTUDISC_WANT, IP_PMTUDISC_DONT, ... IPTOS_LOWDELAY, IPTOS_THROUGHPUT, IPTOS_RELIABILITY, ... MSG_BCAST, MSG_OOB, MSG_TRUNC, ... SHUT_RD, SHUT_RDWR, SHUT_WR INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, ... TCP_CORK, TCP_KEEPALIVE, TCP_NODELAY, ... IN6ADDR_ANY, IN6ADDR_LOOPBACK IPV6_ADD_MEMBERSHIP, IPV6_MTU, IPV6_V6ONLY, ...
🔧 STRUCTURE MANIPULATORS 🔧 FUNCTIONS
getaddrinfo() / getnameinfo() ERROR CONSTANTS
📝 EXAMPLES
🔌 Lookup for connect() 🔍 Making a human-readable string out of an address 🌐 Resolving hostnames into IP addresses ⚙️ Accessing socket options
✍️ AUTHOR

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-06 06:36 @216.73.216.192
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^