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 10: Advanced Socket System Calls

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

Program Statement

One program demonstrating getsockopt/setsockopt, getpeername/getsockname, and scatter/gather I/O with readv/writev — run it against your echo server.

/* advanced.c — run against the echo server */
int fd = socket(AF_INET, SOCK_STREAM, 0);

int rcvbuf; socklen_t ol = sizeof(rcvbuf);
getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &ol);
printf("default SO_RCVBUF = %d\n", rcvbuf);
rcvbuf = 64 * 1024;
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));

connect(fd, (struct sockaddr *)&srv, sizeof(srv));

/* writev: header + payload in ONE call (gather write) */
char hdr[] = "LEN:00011\n", payload[] = "hello world";
struct iovec iov[2] = { {hdr, sizeof(hdr)-1}, {payload, sizeof(payload)-1} };
writev(fd, iov, 2);

/* readv: scatter the echo into two buffers */
char b1[10], b2[64];
struct iovec riov[2] = { {b1, sizeof(b1)}, {b2, sizeof(b2)} };
int n = readv(fd, riov, 2);
printf("readv got %d bytes\n", n);

struct sockaddr_in peer; socklen_t len = sizeof(peer); char ip[64];
getpeername(fd, (struct sockaddr *)&peer, &len);
inet_ntop(AF_INET, &peer.sin_addr, ip, sizeof(ip));
printf("connected to %s:%d\n", ip, ntohs(peer.sin_port));

Record Task

Note the default SO_RCVBUF your system reports, and why writev beats two separate write calls (one syscall, and no chance of TCP sending a tiny segment between header and payload — the Nagle interaction).

Theory Link

Unit 2 "Socket Options & Advanced I/O Functions".