Skip to content

mosakrm0/Layer-4-Load-Balancer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 

Repository files navigation

Layer 4 TCP Load Balancer

To begin With

Used Unix Socket Programming with C language to open socket, listen to connections, bind and fork, look at LoadBalancer.c if you are intrested in the coding area but here is a brief:

// Used libraries:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <signal.h>
// Signal used to prevent zombie proccess
    signal(SIGCHLD, SIG_IGN);

//Creating the socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("Socket failed"); exit(EXIT_FAILURE);
    }

//Allowing port reuse to avoid "Address already in use" errors
    int opt = 1;
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt failed"); exit(EXIT_FAILURE);
    }
// bind and listen functions
    
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("Bind failed"); exit(EXIT_FAILURE);
    }
    
    if (listen(server_fd, 10) < 0) {
        perror("Listen failed"); exit(EXIT_FAILURE);
    }

    printf("Load Balancer is listening on port %d...\n", PORT);

Compilation

gcc LoadBalancer.c -o LoadBalancer

Docker Compose

services:
  backend1:
    image: nginx:alpine
    ports:
      - "8081:80"

  backend2:
    image: nginx:alpine
    ports:
      - "8082:80"

  backend3:
    image: nginx:alpine
    ports:
      - "8083:80"

Docker Compose Up

docker compose up -d

Running the Code we wrote

./LoadBalancer

Testing

curl http://localhost:8080 

or

nc 127.0.0.1 8080
image

About

(C, Unix Sockets, Docker Compose) Built a custom Layer 4 Load Balancer in C using Unix Sockets to distribute network traffic efficiently, used Docker Compose to test traffic routing across multiple Nginx servers and managed processes to ensure high stability.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages