Network Programming — TCP Sockets

Internet-এর নিচের স্তর আপনার হাতে

~55 min Advanced 12 practice problems Live code

1. Why Sockets?

HTTP server, database driver, Slack app, game client — সবগুলোরই নিচে C socket, TCP/UDP। একবার সকেট শিখলে Internet কীভাবে কাজ করে সেটা স্পষ্ট হয়ে যাবে।

2. TCP Server Skeleton

echo_server.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(void) {
    int srv = socket(AF_INET, SOCK_STREAM, 0);
    if (srv < 0) { perror("socket"); return 1; }

    int yes = 1;
    setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

    struct sockaddr_in addr = {0};
    addr.sin_family      = AF_INET;
    addr.sin_port        = htons(8080);
    addr.sin_addr.s_addr = INADDR_ANY;

    bind(srv, (struct sockaddr *)&addr, sizeof addr);
    listen(srv, 10);
    printf("listening on :8080\n");

    while (1) {
        int c = accept(srv, NULL, NULL);
        if (c < 0) continue;
        char buf[1024];
        int n = read(c, buf, sizeof buf);
        if (n > 0) write(c, buf, n);    // echo
        close(c);
    }
    return 0;
}

Online runner-এ network listen blocked/sandboxed থাকতে পারে। নিজের machine-এ compile করে telnet localhost 8080 দিয়ে test করুন।

3. TCP Client

client.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(void) {
    int s = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in a = {0};
    a.sin_family = AF_INET;
    a.sin_port   = htons(8080);
    inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);

    connect(s, (struct sockaddr *)&a, sizeof a);
    const char *msg = "Hello, server!";
    write(s, msg, strlen(msg));

    char buf[128] = {0};
    int n = read(s, buf, sizeof buf - 1);
    if (n > 0) printf("server said: %s\n", buf);
    close(s);
    return 0;
}

4. Concurrency Models

  • Fork per connection — সহজ, heavy at scale।
  • Thread per connection — fork-এর চেয়ে হালকা, তবু limit।
  • select / poll — এক thread-ই অনেক socket handle।
  • epoll (Linux), kqueue (BSD), IOCP (Windows) — modern high-scale।
  • Event loops (libuv, libevent) — উপরের layer।

5. Minimal HTTP/1.0 Server (excerpt)

const char *resp =
    "HTTP/1.0 200 OK\r\n"
    "Content-Type: text/plain\r\n"
    "Content-Length: 13\r\n"
    "\r\n"
    "Hello, world!";
write(c, resp, strlen(resp));

Browser-এ http://localhost:8080 খুললে আপনার C সার্ভার সেই পেজ দেখাবে। Milestone moment।

6. Practice Problems

  1. TCP echo server + matching client.
    Echo server ও client।
    ✨ Show Answer

    Sections 2 ও 3-ই reference। এক terminal-এ server, অন্যটায় client চালান।

  2. Send an int between client & server (htonl / ntohl).
    Int পাঠান (htonl/ntohl)।
    ✨ Show Answer
    uint32_t n = htonl(42);
    write(s, &n, 4);
    // other side:
    read(s, &n, 4);
    int x = ntohl(n);

    Network byte order = big-endian; x86 little-endian। htonl/ntohl platform-independent।

  3. Chat server supporting multiple clients (fork per connection).
    Fork-per-client chat server।
    ✨ Show Answer

    accept-এর পর fork; child communicate করে, parent আবার accept-এ ফিরে যায়। SIGCHLD handler দিয়ে zombie reap।

  4. Chat server using select.
    Select-based chat server।
    ✨ Show Answer

    fd_set-এ সব active fd; select(maxfd+1, &rfds, NULL, NULL, NULL); ready fd loop-এ accept বা read handle।

  5. Minimal HTTP/1.0 server returning static files.
    Static file server।
    ✨ Show Answer

    Request-এর path parse → fopen → file size → HTTP header (Content-Length) + body write। 404 handle।

  6. Handle simple GET with path parsing.
    GET parse।
    ✨ Show Answer

    sscanf(buf, "GET %1023s HTTP/1.%d", path, &ver); root-এ /-কে index.html-এ map করুন।

  7. Add Content-Type detection by extension.
    Extension-ভিত্তিক Content-Type।
    ✨ Show Answer

    Map: .html → text/html, .css → text/css, .js → application/javascript, .png → image/png ইত্যাদি।

  8. Gracefully handle SIGPIPE (broken pipe).
    SIGPIPE handle।
    ✨ Show Answer

    Client disconnect-এর পর write করলে SIGPIPE signal → default kill। Solution: signal(SIGPIPE, SIG_IGN); বা send(..., MSG_NOSIGNAL) ব্যবহার।

  9. Measure requests/sec your server handles.
    Requests/sec measure।
    ✨ Show Answer

    ab -n 10000 -c 100 http://localhost:8080/ (Apache Bench) বা wrk -t4 -c100 -d10s।

  10. Port to epoll on Linux and compare.
    epoll port।
    ✨ Show Answer

    epoll_create1, epoll_ctl দিয়ে fd register, epoll_wait-এ events। thousands of connection-এ select-এর চেয়ে significantly দ্রুত (O(1) per event vs O(n))।

  11. UDP client/server echoing datagrams.
    UDP echo।
    ✨ Show Answer

    SOCK_DGRAM। recvfrom/sendto — connectionless। Server bind; client sendto। Simple, no handshake।

  12. Explain why TCP is reliable and UDP is not.
    TCP reliable, UDP না — কেন?
    ✨ Show Answer

    TCP-এ sequence number, ACK, retransmission, ordering এবং flow control — তাই reliable, ordered, duplicate-free stream। UDP-এ কিছুই নেই — fast, connectionless, lossy — voice/gaming-এ উপযোগী।

Glossary (শব্দকোষ)

TermMeaningবাংলায়
SocketEndpoint of a network connection (a file descriptor).Network connection-এর endpoint।
TCPReliable, ordered, connection-oriented stream protocol.Reliable, ordered, connection-ভিত্তিক protocol।
UDPLightweight connectionless datagram protocol.হালকা, connectionless datagram protocol।
IP AddressNumeric host identifier on the network.হোস্ট চেনানোর সংখ্যাগত ঠিকানা।
Port16-bit number selecting a service on a host.Host-এর কোন service — তা বাছাইয়ের 16-bit সংখ্যা।
Client / ServerOne initiates the connection (client); the other listens (server).একজন connect করে (client), একজন শোনে (server)।
socket()Creates a new socket file descriptor.নতুন socket FD তৈরি।
bind()Binds a socket to a local address and port.Local address+port-এ socket বাঁধা।
listen()Marks a socket as ready to accept connections.Connection accept-এর জন্য সক্রিয় করা।
accept()Pulls a new client connection off the queue.Queue থেকে client-connection নেয়।
connect()Client-side call to start a connection.Client-side connection শুরু।
send / recvTransmit/receive bytes on a socket.Socket-এ byte পাঠানো/পড়া।
htons / ntohlConvert between host and network byte order.Host ও network byte-order রূপান্তর।
sockaddrStruct holding address+port for socket APIs.Address+port ধারণকারী struct।
Three-way HandshakeSYN → SYN-ACK → ACK that establishes a TCP connection.TCP connection স্থাপনের তিন ধাপ।
epoll / selectMultiplex many sockets in one thread.এক thread-এ অনেক socket একসাথে দেখা।

Summary — Module 39

socket → bind → listen → accept → read/write → close। Client: socket → connect → read/write → close। Scale-এর জন্য epoll। আপনার প্রথম HTTP সার্ভার একটি rite of passage।

Next Module → Capstone — একটি বাস্তব সিস্টেম।