[c] Sockets - How to find out what port and address I'm assigned

I'm having trouble figuring this out - I'm working with sockets in C using this guide - http://binarii.com/files/papers/c_sockets.txt

I'm trying to automatically get my ip and port using:

server.sin_port = 0;              /* bind() will choose a random port*/
server.sin_addr.s_addr = INADDR_ANY;  /* puts server's IP automatically */
...
...
bind(int fd, struct sockaddr *my_addr,int addrlen); // Bind function

After a successful bind, how do I find out what IP and Port I'm actually assigned?

This question is related to c sockets tcp

The answer is


The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.


Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to sockets

JS file gets a net::ERR_ABORTED 404 (Not Found) mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 TypeError: a bytes-like object is required, not 'str' Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED No connection could be made because the target machine actively refused it 127.0.0.1 Sending a file over TCP sockets in Python socket connect() vs bind() java.net.SocketException: Connection reset by peer: socket write error When serving a file How do I use setsockopt(SO_REUSEADDR)?

Examples related to tcp

What does "app.run(host='0.0.0.0') " mean in Flask What is the difference between HTTP 1.1 and HTTP 2.0? Sending a file over TCP sockets in Python Telnet is not recognized as internal or external command How to open port in Linux adb connection over tcp not working now Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured] How do I debug error ECONNRESET in Node.js? Differences between TCP sockets and web sockets, one more time Is SMTP based on TCP or UDP?