[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: IP address without hostname



Peter Bartosch <peter@bartosch.net> [2002-08-17 17:25:58 +0200]:
> i'm searching for a function to gather the IP adresses from the  
> interfaces of a computer - without having the hostname nor any other  
> information ...  

Curiosity has me asking, if you care to share otherwise don't worry
about it, for what purpose do you need to know the host IP address?

> > I found this somewhere on another maillist. It uses ioctl() to poll some 
> > information.

Note that it is possible for the list of IPs returned to vary over
time.  Interfaces can be brought up and down while the computer is
operating.  If the interface is on a PCMCIA in a laptop then the
network can be established or the network can be brought down at any
time.

Therefore programs that deal with actual interfaces need to be
prepared for the comings and goings of the network.  In my program I
recheck for new interfaces to appear every five minutes as that is
plenty fine for my particular and unique purpose.  Your case will need
your own judgement.  If an interface suddenly goes away I react to
that by removing the interface from my program structures.  It is not
an error but just a normal event.

Also, if you ask it for the flags you can tell which devices are
loopback devices.  I will include a snippet at the end of this message
that will show how to see if the interface is up and if the interface
is loopback and in my case if it has broadcast capability.

Bob


  /*
   * An array of devices were returned.  Which ones are up right now and
   * have broadcast capability?
   */
  numdevs = ifc_conf.ifc_len / sizeof (struct ifreq);
  for (i = 0; i < numdevs; i++)
    {
      /* devptr points into an array of ifreq structs. */
      devptr = &ifc_conf.ifc_req[i];

      if (devptr->ifr_addr.sa_family != AF_INET)
        continue;

      if (ioctl(sd,SIOCGIFFLAGS,devptr) < 0)
        {
          fprintf(stderr,"Error: Unable to get device interface flags.\n");
	  perror("ioctl");
	  close(sd);
	  return -1;
	}

      if ((devptr->ifr_flags & IFF_LOOPBACK) != 0)
        continue;

      if ((devptr->ifr_flags & IFF_UP) == 0)
        continue;

      if ((devptr->ifr_flags & IFF_BROADCAST) == 0)
        continue;

Attachment: pgpAAdl0r5JN7.pgp
Description: PGP signature


Reply to: