Build your own Redis
The Guide below is a sequence of tasks which will be divided into various levels and ultimately will help you build your own REDIS
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main() {
// Disable output buffering
setbuf(stdout, NULL);
setbuf(stderr, NULL);
// Debugging message
printf("Logs from your program will appear here!\n");
int server_fd, client_addr_len;
struct sockaddr_in client_addr;
// Step 1: Create a socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
printf("Socket creation failed: %s...\n", strerror(errno));
return 1;
}
// Step 2: Set socket options
int reuse = 1;
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
printf("SO_REUSEADDR failed: %s \n", strerror(errno));
return 1;
}
// Step 3: Define server address
struct sockaddr_in serv_addr = {
.sin_family = AF_INET,
.sin_port = htons(6379),
.sin_addr = { htonl(INADDR_ANY) },
};
// Step 4: Bind the socket
if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) != 0) {
printf("Bind failed: %s \n", strerror(errno));
return 1;
}
// Step 5: Listen for connections
int connection_backlog = 5;
if (listen(server_fd, connection_backlog) != 0) {
printf("Listen failed: %s \n", strerror(errno));
return 1;
}
// Step 6: Accept a client connection
printf("Waiting for a client to connect...\n");
client_addr_len = sizeof(client_addr);
accept(server_fd, (struct sockaddr *) &client_addr, &client_addr_len);
printf("Client connected\n");
// Step 7: Close the server socket
close(server_fd);
return 0;
}Let's break down each part to understand its functionality, especially for someone new to socket programming.
Last updated