In this article, we'll be discussing Linux sockets and network programming. We'll cover what they are, how they work, and some common use cases. We'll also provide some code examples in C to illustrate how to use them.
In computer networking, a socket is an endpoint of a bidirectional or unidirectional data communication channel. Sockets can be used to establish a connection between two computers, which can then be used to exchange data.
Sockets can be either stream-oriented or datagram-oriented. Stream-oriented sockets provide a reliable, ordered, and error-checked connection between two computers. Datagram-oriented sockets, on the other hand, are connectionless and do not guarantee that the data will be delivered in the same order that it was sent.
Sockets work by creating a socket object on one computer, which is bound to a port number. This socket object can then be used to connect to a socket on another computer, which is also bound to a port number. Once a connection is established, data can be exchanged between the two computers.
There are many reasons why you might want to use sockets in your applications. Some common use cases include:
Here are some code examples in C to illustrate how to use sockets.
To create a socket, you need to use the socket()
function. This function takes three arguments:
AF_INET
for IPv4 or AF_INET6
for IPv6)SOCK_STREAM
for a stream-oriented socket or SOCK_DGRAM
for a datagram-oriented socket)IPPROTO_TCP
for TCP or IPPROTO_UDP
for UDP)int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
To connect to a socket, you need to use the connect()
function. This function takes three arguments:
struct sockaddr *
)struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
To send data, you need to use the send()
function. This function takes three arguments:
void *
)char buf[1024];
send(sockfd, buf, sizeof(buf), 0);
To receive data, you need to use the recv()
function. This function takes four arguments:
void *
)MSG_WAITALL
to wait for all the data to arrive)char buf[1024];
recv(sockfd, buf, sizeof(buf), MSG_WAITALL);
To close a socket, you need to use the close()
function. This function takes a single argument:
close(sockfd);