Welcome to our deep dive into C Socket Programming! This tutorial is designed for both beginners and intermediates, so let's get started.
Socket programming is a method of communication between two devices over a network, using sockets. It's fundamental in network programming and allows C programs to communicate with other devices over the internet.
A socket is an endpoint of a two-way communication link between two programs running on the network. Sockets can be used to send and receive data over this link.
Let's create a simple server and client program to get familiar with sockets.
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
// Create a socket
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
// Configure the address and port for the server
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
server_addr.sin_addr.s_addr = INADDR_ANY;
// Bind the socket to the address and port
bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
// Listen for incoming connections
listen(server_socket, 3);
// Accept an incoming connection
int client_socket = accept(server_socket, NULL, NULL);
// Receive a message from the client
char buffer[1024];
recv(client_socket, buffer, sizeof(buffer), 0);
// Print the received message
printf("Received message: %s\n", buffer);
return 0;
}#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
// Create a socket
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
// Configure the address and port for the server
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8888);
// Convert IPv4 address into a binary format
char server_ip[] = "127.0.0.1";
inet_pton(AF_INET, server_ip, &server_addr.sin_addr);
// Connect to the server
connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
// Send a message to the server
char message[] = "Hello, Server!";
send(client_socket, message, sizeof(message), 0);
return 0;
}What is Socket Programming?
This is just the beginning of our socket programming journey! In the next lessons, we'll dive deeper into advanced topics, so stay tuned. Happy coding! 💡