Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Experiment 1: Create Sockets for Sending and Receiving Data

Lesson 2 of 11 in the free Network Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Program Statement

Create a pair of UDP sockets — a receiver bound to a well-known port and a sender that transmits a message and reads the reply.

/* udp_recv.c — receiver */
int main(void) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in addr = {0}, cli; socklen_t len = sizeof(cli);
    addr.sin_family = AF_INET; addr.sin_port = htons(9877);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    bind(fd, (struct sockaddr *)&addr, sizeof(addr));
    char buf[1024];
    int n = recvfrom(fd, buf, sizeof(buf)-1, 0, (struct sockaddr *)&cli, &len);
    buf[n] = '\0';
    printf("received: %s\n", buf);
    sendto(fd, "got it!", 7, 0, (struct sockaddr *)&cli, len);
    close(fd); return 0;
}

/* udp_send.c — sender */
int main(void) {
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in srv = {0};
    srv.sin_family = AF_INET; srv.sin_port = htons(9877);
    inet_pton(AF_INET, "127.0.0.1", &srv.sin_addr);
    sendto(fd, "hello sockets", 13, 0, (struct sockaddr *)&srv, sizeof(srv));
    char buf[1024];
    int n = recv(fd, buf, sizeof(buf)-1, 0);          /* reply */
    buf[n] = '\0'; printf("server says: %s\n", buf);
    close(fd); return 0;
}

Running It

  1. Terminal 1: gcc udp_recv.c -o udp_recv && ./udp_recv
  2. Terminal 2: gcc udp_send.c -o udp_send && ./udp_send

Theory Link

Unit 1 "Elementary TCP Sockets" + Unit 2 "Elementary UDP Sockets". Note in your record: the receiver must bind to a known port; the sender's port is assigned implicitly (ephemeral) on the first sendto.