[Ilugc] Find IP address of a machine

  • From: girishvenkatachalam@xxxxxxxxx (Girish Venkatachalam)
  • Date: Tue Oct 24 13:24:56 2006

On Tue, Oct 24, 2006 at 07:59:08AM +0200, Binand Sethumadhavan wrote:

On 24/10/06, Girish Venkatachalam <girishvenkatachalam@xxxxxxxxx> wrote:
Well, a given machine could have several different IP addresses, so
you need to be a bit more specific than that.
There are both multi homed and single interface having mutiple IP 
addresses problem.

There are also NAT, multicasting, hot-standby protocols like
VRRP/CARP, load-balancing etc. that causes an IP address to be
associated with a given machine.

The point is that an IP address is not a property of the machine, so a
question like "how do I figure out the OP address of a machine?" is
meaningless. IP addresses are properties of TCP/IP connections, not of
machines/computers/hardware.
Yes I agree but practically there is no need to complicate things so much.

If you trunk,bridge,vlan or carp your interface then your IP address cannot be 
determined easily but AFAIK ifconfig should work.

I must be wrong, if so please correct.

Can you tell me how NAT and multicasting affect this? Or did you mean something 
else? Anyway that is not important.

IP address is assigned either manually, by DHCP,PPP,PPPoX etc...

NAT afffects connections to the external world. Ok now I get what you mean.

If you run a server from inside a NATed machine, then you got to port forward 
it and your RFC1918 address really doesn't matter...

Now, what about multicasting? Sorry I don't know.


Given that, the way to figure out IP addresses at both ends of a
connection are the pair of system calls getsockname/getpeername
(perldoc -f for their usage details).
All this is fine and dandy but getpeername() works very well practically.

getsockname() doesn't. Try it and you will know what I mean.

It always returns 0.0.0.0 for INADDR_ANY. Now, if you bind it manually then you 
don't need this call in the first place...

I think this is a recognized defect in the design. Hence the need to put hacks 
like ifconfig.

regards,
Girish

PS:- Can you get this script to work?


use Socket;

my $proto = 0;
my $port = 1245;
   socket(Server, PF_INET, SOCK_STREAM, $proto) ;
  setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1));  
  bind(Server, sockaddr_in($port, INADDR_ANY)) ; 
 listen(Server,SOMAXCONN); 


        $mysockaddr = getsockname(Server);
        ($port, $myaddr) = sockaddr_in($mysockaddr);
                                                                            
printf "Connect to %s [%s]\n", scalar gethostbyaddr($myaddr, AF_INET), 
inet_ntoa($myaddr)

Other related posts: