The socket() system call creates a new socket.
#include <sys/socket.h>
int socket
(int domain, int type, int protocol);
Returns file descriptor on success, or -1 on error
The domain argument specifies the communication domain for the socket. The type argument specifies the socket type. This argument is usually specified as either SOCK_STREAM
, to create a stream socket, or SOCK_DGRAM
, to create a datagram socket.
The protocol argument is always specified as 0 for the socket types we describe in this book. Nonzero protocol values are used with some socket types that we don’t describe. For example, protocol is specified as IPPROTO_RAW
for raw sockets (SOCK_RAW
).
On success, socket() returns a file descriptor used to refer to the newly created socket in later system calls.
Starting with kernel 2.6.27, Linux provides a second use for the type argument, by allowing two nonstandard flags to be ORed with the socket type. The SOCK_CLOEXEC
flag causes the kernel to enable the close-on-exec flag (FD_CLOEXEC
) for the new file descriptor. This flag is useful for the same reasons as the open() O_CLOEXEC
flag described in . The SOCK_NONBLOCK flag causes the kernel to set the O_NONBLOCK
flag on the underlying open file description, so that future I/O operations on the socket will be nonblocking. This saves additional calls to fcntl() to achieve the same result.