[uClinux-dev] retriving a dhcp assigned gateway

David Felsenthal david at felsenthal.org
Mon Mar 24 12:56:25 EST 2003


Massimiliano Cialdi wrote:
> How can I retrive the gateways ip address assigned to my host by a dhcp
> server? 
> I use dhcpcd-new, and I think I need an ioctl call with SIOCG*.
> 
> 
> thanks
> 
> 
Unix network Programming by W. Richar Stevens volume 1 is an extremely 
helpful book.

here's one way ...

<include a whole lot of header files here>

int get_if_address(int request,char *str,int sockfd)
{
   int  sockfd;
   struct sockaddr_in	*sin;
   struct ifreq          myifreq;
   char *p;

   sockfd = socket(AF_INET, SOCK_DGRAM, 0);
   if (sockfd == -1)
     {
       return -1;
     }

   strcpy(myifreq.ifr_name ,"eth0");
   if (ioctl(sockfd,request,&myifreq) < 0)
     {
       return -1;;
     };

   switch(request)
     {
     case SIOCGIFADDR:
       sin = (struct sockaddr_in *) &(myifreq.ifr_addr);
       if (!inet_ntop(AF_INET,&sin->sin_addr,str,sizeof("255.255.255.255")))
	{
	  return -1;
	}
       break;

     case SIOCGIFNETMASK:
       sin = (struct sockaddr_in *) &(myifreq.ifr_netmask);
       if (!inet_ntop(AF_INET,&sin->sin_addr,str,sizeof("255.255.255.255")))
	{
	  return -1;
	}
       break;

     case SIOCGIFHWADDR:
       p = (char *) &(myifreq.ifr_hwaddr.sa_data);
 
sprintf(str,"%.2hhx:%.2hhx:%.2hhx:%.2hhx:%.2hhx:%.2hhx",p[0],p[1],p[2],p[3],p[4],p[5]);
       break;

     default:
       return -1;
     }
   return 0;

}


David




More information about the uClinux-dev mailing list