Introduction to Socket Programming in C


Introduction

Socket programming is a fundamental concept for building networked applications in C. Sockets provide a communication interface between computers over a network, enabling data exchange. This guide introduces socket programming in C and includes sample code to help you understand the basics.


What Are Sockets?

Sockets are endpoints for network communication. They allow programs to send and receive data over a network using various communication protocols, such as TCP and UDP. Sockets can be used for various networking tasks, including creating servers and clients, transferring data, and more.


Socket Types

There are two primary types of sockets in socket programming:

  • Stream Sockets (TCP): These provide a reliable, connection-oriented communication channel. Data is transmitted in a stream, ensuring data integrity.
  • Datagram Sockets (UDP): These provide connectionless, unreliable communication. Data is sent as discrete packets, which can be faster but may not guarantee delivery.

Sample Code - Creating a Simple TCP Server

Let's create a simple C program that acts as a TCP server, accepting connections and receiving data from clients.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
int main() {
int serverSocket, clientSocket;
struct sockaddr_in serverAddr, clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
char buffer[1024];
// Create a socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket < 0) {
perror("Error in socket creation");
exit(1);
}
// Initialize server address
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(8080);
// Bind the socket
if (bind(serverSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
perror("Error in binding");
exit(1);
}
// Listen for incoming connections
listen(serverSocket, 5);
printf("Server listening on port 8080...\n");
// Accept client connections
clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, &clientAddrLen);
// Receive data from the client
recv(clientSocket, buffer, sizeof(buffer), 0);
printf("Received data from client: %s\n", buffer);
// Close sockets
close(clientSocket);
close(serverSocket);
return 0;
}

Conclusion

Socket programming in C is essential for building networked applications. This guide introduced the concept of sockets and provided a sample C program that acts as a simple TCP server. As you continue to explore socket programming, you can create more complex networked applications and gain a deeper understanding of network communication.