Socket programming in C is a fundamental technique for creating network applications. It enables processes to communicate over a network, forming the backbone of client-server architectures.
Sockets are endpoints for communication between two nodes on a network. They provide a standardized interface for network programming, allowing data exchange between applications running on different machines.
C socket programming involves several key operations:
C supports two main types of sockets:
To create a socket in C, use the socket()
function:
#include <sys/socket.h>
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == -1) {
// Error handling
}
This creates a TCP socket. For UDP, replace SOCK_STREAM
with SOCK_DGRAM
.
Binding associates a socket with a specific address and port:
#include <netinet/in.h>
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8080);
if (bind(socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
// Error handling
}
For server applications, you need to listen for incoming connections:
if (listen(socket_fd, 5) == -1) {
// Error handling
}
int client_fd = accept(socket_fd, NULL, NULL);
if (client_fd == -1) {
// Error handling
}
Use send()
and recv()
functions for data transfer:
char buffer[1024];
ssize_t bytes_sent = send(client_fd, "Hello, client!", 14, 0);
ssize_t bytes_received = recv(client_fd, buffer, sizeof(buffer), 0);
Always close sockets when you're done:
#include <unistd.h>
close(socket_fd);
To deepen your understanding of C socket programming, explore these related topics:
Socket programming in C is a powerful tool for network communication. By mastering these concepts, you'll be well-equipped to develop sophisticated networked applications.