Subject: Re: Finding the correct interface for a packet
To: Ken Hornstein <kenh@cmf.nrl.navy.mil>
From: Stefan Grefen <grefen@hprc.tandem.com>
List: tech-net
Date: 12/02/1998 10:41:40
In message <199812020444.XAA06678@ginger.cmf.nrl.navy.mil>  Ken Hornstein wrote:
> > 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".

Nice idea,
it should work most of the time on NetBSD, but. AFAIK it is not
portable. Some systems assign the ip-addr in ip_output, so you'll get
a NULLHOST back.
On NetBSD it fails if the route is changed ... which reminds why one
shouldn't connect UDP sockets, the may send packets with wrong  
src-addresses if the routing changes between calls. 

Stefan

> 
> --Ken

--
Stefan Grefen                                Tandem Computers Europe Inc.
grefen@hprc.tandem.com                       High Performance Research Center
 --- Hacking's just another word for nothing left to kludge. ---