Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

tcp

sockets

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?

like image 275
stringo0 Avatar asked Oct 28 '10 19:10

stringo0


People also ask

What is socket address and port address?

A socket uniquely identifies the endpoint of a communication link between two application ports. A port represents an application process on a TCP/IP host, but the port number itself does not indicate the protocol being used: TCP, UDP, or IP.

How do I find the client port number for server socket programming?

This can be done using a bind() system call specifying a particular port number in a client-side socket. Below is the implementation Server and Client program where a client will be forcefully get assigned a port number.

How do you find a port number?

Generate UPC at the point of sale of recipient operator. SMS the word 'PORT' (which shall be case-insensitive, i.e., it can be 'port' or 'Port' etc.) followed by a space and the ten-digit mobile number which is to be ported, to 1900. The UPC will be received through SMS on the mobile of the Subscriber.


2 Answers

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin; socklen_t len = sizeof(sin); if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)     perror("getsockname"); else     printf("port number %d\n", ntohs(sin.sin_port)); 

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

like image 102
mark4o Avatar answered Sep 19 '22 18:09

mark4o


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.

like image 41
user207421 Avatar answered Sep 19 '22 18:09

user207421