home *** CD-ROM | disk | FTP | other *** search
/ ARM Club 3 / TheARMClub_PDCD3.iso / hensa / unix / unixlib_1 / !UnixLib37_netlib_netlib_c_inet_addr < prev    next >
Encoding:
Text File  |  1996-07-28  |  1.6 KB  |  72 lines

  1. /****************************************************************************
  2.  *
  3.  * $Source$
  4.  * $Date$
  5.  * $Revision$
  6.  * $State$
  7.  * $Author$
  8.  *
  9.  * $Log$
  10.  ***************************************************************************/
  11.  
  12. static const char rcs_id[] = "$Id$";
  13.  
  14. #include <stdio.h>
  15.  
  16. #include <arpa/inet.h>
  17. #include <netinet/in.h>
  18.  
  19. /*
  20.  * Extract an internet address in network byte order from a string
  21.  */
  22. u_long
  23. inet_addr (const char *cp)
  24. {
  25.   u_long octet1;
  26.   u_long octet2;
  27.   u_long octet3;
  28.   u_long octet4;
  29.   int octets;
  30.  
  31.   /* Parse the string */
  32.   octets = sscanf (cp, "%i.%i.%i.%i", (int *) &octet1, (int *) &octet2,
  33.            (int *) &octet3, (int *) &octet4);
  34.  
  35.   switch (octets)
  36.     {
  37.     case 1:
  38.       /* Address is in 'a' format so break it up 'a' */
  39.       octet4 = octet1 & 0xff;
  40.       octet3 = (octet1 >> 8) & 0xff;
  41.       octet2 = (octet1 >> 16) & 0xff;
  42.       octet1 = (octet1 >> 24) & 0xff;
  43.       break;
  44.     case 2:
  45.       /* Address is in 'a.b' format so break up 'b' */
  46.       octet4 = octet2 & 0xff;
  47.       octet3 = (octet2 >> 8) & 0xff;
  48.       octet2 = (octet2 >> 16) & 0xff;
  49.       break;
  50.     case 3:
  51.       /* Address is in 'a.b.c' format so break up 'c' */
  52.       octet4 = octet3 & 0xff;
  53.       octet3 = (octet3 >> 8) & 0xff;
  54.       break;
  55.     case 4:
  56.       /* Address is in 'a.b.c.d' format so leave it as is */
  57.       break;
  58.     default:
  59.       /* Error */
  60.       return (u_long) - 1;
  61.     }
  62.  
  63.   /* Validate the octet values */
  64.   if (octet1 > 255 || octet2 > 255 || octet3 > 255 || octet4 > 255)
  65.     {
  66.       return (u_long) - 1;
  67.     }
  68.  
  69.   /* Put the address together */
  70.   return (octet4 << 24) | (octet3 << 16) | (octet2 << 8) | octet1;
  71. }
  72.