Fundamental Socket Programming Concepts
At the core of network socket programming in Linux are several fundamental concepts and functions that developers need to understand. These include:
Socket Creation
The socket()
function is used to create a new socket. It takes three arguments: the address family (e.g., AF_INET
for IPv4), the socket type (e.g., SOCK_STREAM
for TCP, SOCK_DGRAM
for UDP), and the protocol (usually 0
to let the system choose the default).
int socket(int domain, int type, int protocol);
Socket Addressing
Sockets are associated with a specific address and port number. The struct sockaddr_in
data structure is used to represent the address information for IPv4 sockets.
struct sockaddr_in {
sa_family_t sin_family; // Address family (e.g., AF_INET)
in_port_t sin_port; // Port number
struct in_addr sin_addr; // IPv4 address
};
Socket Binding
The bind()
function is used to associate a socket with a specific address and port number.
int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
Socket Listening
For server-side sockets, the listen()
function is used to put the socket in a listening state, allowing it to accept incoming connections.
int listen(int sockfd, int backlog);
Socket Accepting
The accept()
function is used to accept an incoming connection on a listening socket. It returns a new socket file descriptor that can be used for communication.
int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
Socket Communication
The send()
and recv()
functions (or their variants, such as write()
, read()
, sendto()
, and recvfrom()
) are used to send and receive data over a connected socket.
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
By understanding these fundamental socket programming concepts and functions, you can start building network-based applications in Linux, ranging from simple client-server programs to complex distributed systems.