Untitled

 avatar
unknown
plain_text
5 months ago
2.8 kB
3
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 9999
#define BACKLOG 5  // Number of pending connections to allow

int main() {
    int fd, confd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);
    
    // Create socket
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0) {
        perror("Error opening socket");
        exit(1);
    }

    // Initialize server address structure
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;  // Bind to any IP address
    server_addr.sin_port = htons(PORT);  // Set port number

    // Bind socket to address
    if (bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("Error binding socket");
        close(fd);
        exit(1);
    }

    // Listen for incoming connections
    if (listen(fd, BACKLOG) < 0) {
        perror("Error listening");
        close(fd);
        exit(1);
    }

    printf("Server listening on port %d...\n", PORT);

    // Main server loop
    while (1) {
        // Accept incoming connection
        confd = accept(fd, (struct sockaddr *)&client_addr, &client_len);
        if (confd < 0) {
            perror("Error accepting connection");
            continue;  // Continue listening for new connections
        }

        // Fork to handle the connection in a new process
        pid_t pid = fork();
        
        if (pid < 0) {
            perror("Error forking");
            close(confd);
            continue;  // Continue accepting new connections
        }

        if (pid == 0) {
            // Child process
            close(fd);  // Close the server socket in the child process
            
            // Handle the client (reading/writing data)
            char buffer[1024];
            ssize_t n;

            // Example: Reading from client and sending back a response
            while ((n = read(confd, buffer, sizeof(buffer))) > 0) {
                write(confd, buffer, n);  // Echo back the data
            }

            if (n < 0) {
                perror("Error reading from client");
            }
            
            // Close the connection
            close(confd);
            exit(0);  // Exit child process after handling the client
        } else {
            // Parent process
            close(confd);  // Parent doesn't need the client socket anymore
        }
    }

    // Close the server socket (this will never be reached in this infinite loop)
    close(fd);
    return 0;
}
Editor is loading...
Leave a Comment