Subject: Re: Finding the correct interface for a packet
To: Ken Hornstein <kenh@cmf.nrl.navy.mil>
From: Perry E. Metzger <perry@piermont.com>
List: tech-net
Date: 12/02/1998 00:05:31
Cool hack! I hadn't thought of that!

.pm

Ken Hornstein writes:
> > I'm searching for an example userland source which takes an IP address
> > as argument and returns the network interface which would be used to
> > send a packet to the supplied IP address.
> > 
> > Do we have something like that somewhere in our sources? If we don't
> > has anybody ever written something like that?
> 
> I just tried this, and it seems to work:
> 
> - Create a UDP socket
> - bind() it to a local port
> - connect() it to the "supplied IP address"
> - getsockname() on the socket
> 
> The returned struct sockaddr from getsockname() will contain the
> IP address of the interface that the supplied IP address will be
> using.  From there, you should be able to figure out the interface name
> by walking the interface list.
> 
> "No fuss, no muss".
> 
> --Ken