The Linux Programming Interface

(nextflipdebug5) #1
Sockets: Introduction 1153

Socket I/O can be performed using the conventional read() and write() system calls,
or using a range of socket-specific system calls (e.g., send(), recv(), sendto(), and
recvfrom()). By default, these system calls block if the I/O operation can’t be com-
pleted immediately. Nonblocking I/O is also possible, by using the fcntl() F_SETFL
operation (Section 5.3) to enable the O_NONBLOCK open file status flag.
On Linux, we can call ioctl(fd, FIONREAD, &cnt) to obtain the number of
unread bytes available on the stream socket referred to by the file descriptor
fd. For a datagram socket, this operation returns the number of bytes in the
next unread datagram (which may be zero if the next datagram is of zero
length), or zero if there are no pending datagrams. This feature is not speci-
fied in SUSv3.

56.2 Creating a Socket: socket()


The socket() system call creates a new socket.

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 Section 4.3.1. 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.

56.3 Binding a Socket to an Address: bind()


The bind() system call binds a socket to an address.

#include <sys/socket.h>

int socket(int domain, int type, int protocol);
Returns file descriptor on success, or –1 on error

#include <sys/socket.h>

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
Returns 0 on success, or –1 on error
Free download pdf