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%

Experiments 2 & 3: Obtain the Local & Remote Socket Address

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

Program Statement

Connect a TCP socket to a remote host, then introspect both ends of the connection — getsockname for the local address, getpeername for the remote address. (The experiment list includes this twice — demonstrate both directions.)

/* sockaddrs.c — connect somewhere, then introspect both ends */
int main(void) {
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in srv = {0};
    srv.sin_family = AF_INET; srv.sin_port = htons(80);
    inet_pton(AF_INET, "93.184.216.34", &srv.sin_addr);   /* example.com */
    connect(fd, (struct sockaddr *)&srv, sizeof(srv));

    struct sockaddr_in local, remote; socklen_t len; char ip[INET_ADDRSTRLEN];

    len = sizeof(local);
    getsockname(fd, (struct sockaddr *)&local, &len);     /* LOCAL end  */
    inet_ntop(AF_INET, &local.sin_addr, ip, sizeof(ip));
    printf("local:  %s:%d\n", ip, ntohs(local.sin_port)); /* ephemeral port! */

    len = sizeof(remote);
    getpeername(fd, (struct sockaddr *)&remote, &len);    /* REMOTE end */
    inet_ntop(AF_INET, &remote.sin_addr, ip, sizeof(ip));
    printf("remote: %s:%d\n", ip, ntohs(remote.sin_port));
    close(fd); return 0;
}

Record Task

Run the program twice — watch the local ephemeral port change between runs while the remote end stays fixed.

Theory Link

Unit 1 "Socket Address Structures" — this is the value-result argument in action: len is passed in with the buffer size and comes back with the actual address length.