home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / N / TCPIP / NETKIT-B.05 / NETKIT-B / NetKit-B-0.05 / talk.FvK < prev   
Encoding:
Text File  |  1994-05-23  |  1.7 KB  |  60 lines

  1. --- get_addrs.c
  2. +++ get_addrs.c    1994/02/23 12:41:31
  3. @@ -44,11 +44,33 @@
  4.  #include <stdio.h>
  5.  #include "talk_ctl.h"
  6.  
  7. +/*
  8. + * Hah.  BSD folks may have thought too simple on this one.
  9. + * If you are a multihomed host, this program will miserably fail,
  10. + * as it will use the IP address of "hostname" as the source of the
  11. + * messages, not the address of the interface over which the packet
  12. + * will be routed.
  13. + *
  14. + * With Linux NET-2E, a possible solution is to perform an UDP CONNECT
  15. + * operation on a socket, so the kernel sets the correct source address
  16. + * of the socket's packets.  Then we do a getsockname on that socket,
  17. + * and voila... we have the correct source address!
  18. + *
  19. + * Note that this only works with NET-2E BETA-4 and newer kernels.
  20. + */
  21.  get_addrs(my_machine_name, his_machine_name)
  22.      char *my_machine_name, *his_machine_name;
  23.  {
  24.      struct hostent *hp;
  25.      struct servent *sp;
  26. +#ifdef __linux__
  27. +    struct sockaddr_in sin;
  28. +    struct sockaddr_in foo;
  29. +    int sock, i;
  30. +
  31. +    /* If socket fails, code will see it. */
  32. +    sock = socket(AF_INET, SOCK_DGRAM, 0);
  33. +#endif
  34.  
  35.      msg.pid = htonl(getpid());
  36.      /* look up the address of the local host */
  37. @@ -81,4 +103,22 @@
  38.          exit(-1);
  39.      }
  40.      daemon_port = sp->s_port;
  41. +#ifdef __linux__
  42. +    sin.sin_family = AF_INET;
  43. +    sin.sin_addr.s_addr = his_machine_addr.s_addr;
  44. +    sin.sin_port = sp->s_port;
  45. +
  46. +    /* Now here is the trick.  We connect to the other side. */
  47. +    if ((sock >= 0) &&
  48. +        (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) == 0)) {
  49. +        /* Bingo.  Now fetch the address. */
  50. +        foo = sin;
  51. +        i = sizeof(foo);
  52. +        if (getsockname(sock, (struct sockaddr *) &foo, &i) == 0) {
  53. +            my_machine_addr = foo.sin_addr;
  54. +        }
  55. +    }
  56. +    /* Loose the socket. */
  57. +    (void) close(sock);
  58. +#endif
  59.  }
  60.