Get IP address from socket descriptor?

2019-02-22 08:53发布

问题:

I've opened a TCP socket server (I've omitted a few stuff, it is taken from here

sockfd = socket(p->ai_family, p->ai_socktype,
            p->ai_protocol))

Is it possible to get the IP address of the server from sockfd? If not where should I look?

EDIT: I want to know the address of the server (this is before any client connects).

回答1:

If you want to know who's at the other end of your socket you can use getpeername in Linux. getsockname will tell you who you are. You decide what address you want your server to sit on initially though, at bind time.

You may also find this SO question useful: bind socket to network interface

And the book "Unix Network Programming, vol 1", by W. Richard Stevens.



回答2:

You can't use the socket to get the server's address before a client connects, because it isn't known.

In principle, a host may have multiple IPs. The IP used for a connection to a server is the one belonging to the interface, through which the connection arrived. Until a connection arrives, it isn't known.
Even if you have only one IP, connections may arrive from within the machine, in which case the address would be 127.0.0.1.

So the listening socket has no information about the IP.
You'll need to find what interfaces the machine has, and what's their IPs.



回答3:

The address of the server is up to you.

Depends on which parameters are passed to the bind() function.

You can specify a single ip or bind your socket to every address of your host.

Look at the Bind man page



回答4:

The address of the server is the one that was passed to the successfull call to bind() (as shown in the source you linked).