Subject: Re: Finding the correct interface for a packet
To: Matthias Scheler <tron@lyssa.owl.de>
From: Andrew Brown <twofsonet@graffiti.com>
List: tech-net
Date: 12/01/1998 19:23:47
>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?

see route(8).  :)

for example, first a remote host, then localhost, then the the
machine's primary address.

% route get 198.6.1.1
   route to: cache00.ns.uu.net
destination: default
       mask: default
    gateway: cisco.echonyc.com
  interface: de0
      flags: <UP,GATEWAY,DONE,STATIC>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0         0         0 

% route get 127.0.0.1
   route to: localhost
destination: localhost
  interface: lo0
      flags: <UP,HOST,DONE>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0         0         0 

% route get 198.67.15.13
   route to: noc.untraceable.net
destination: noc.untraceable.net
  interface: lo0
      flags: <UP,HOST,DONE,LLINFO>
 recvpipe  sendpipe  ssthresh  rtt,msec    rttvar  hopcount      mtu     expire
       0         0         0         0         0         0         0         0 

  in each case, the "interface" line is what you want.  i, at one
point, snarfed pieces of code from route.c and cobbled some other bits
together for just this purpose.

the snag: it uses routing sockets, which means it needs to be root.

-- 
|-----< "CODE WARRIOR" >-----|
codewarrior@daemon.org             * "ah!  i see you have the internet
twofsonet@graffiti.com (Andrew Brown)                that goes *ping*!"
andrew@crossbar.com       * "information is power -- share the wealth."