home *** CD-ROM | disk | FTP | other *** search
- #include <stdio.h>
-
- #include "arpa/inet.h"
- #include "netinet/in.h"
-
- /*
- * Extract an internet address in network byte order from a string
- */
- u_long inet_addr(const char *cp)
- {
- u_long octet1;
- u_long octet2;
- u_long octet3;
- u_long octet4;
- int octets;
-
- /* Parse the string */
- octets = sscanf(cp, "%i.%i.%i.%i", (int *)&octet1, (int *)&octet2,
- (int *)&octet3, (int *)&octet4);
-
- switch (octets)
- {
- case 1:
- /* Address is in 'a' format so break it up 'a' */
- octet4 = octet1 & 0xff;
- octet3 = (octet1 >> 8) & 0xff;
- octet2 = (octet1 >> 16) & 0xff;
- octet1 = (octet1 >> 24) & 0xff;
- break;
- case 2:
- /* Address is in 'a.b' format so break up 'b' */
- octet4 = octet2 & 0xff;
- octet3 = (octet2 >> 8) & 0xff;
- octet2 = (octet2 >> 16) & 0xff;
- break;
- case 3:
- /* Address is in 'a.b.c' format so break up 'c' */
- octet4 = octet3 & 0xff;
- octet3 = (octet3 >> 8) & 0xff;
- break;
- case 4:
- /* Address is in 'a.b.c.d' format so leave it as is */
- break;
- default:
- /* Error */
- return (u_long)-1;
- }
-
- /* Validate the octet values */
- if (octet1 > 255 || octet2 > 255 || octet3 > 255 || octet4 > 255)
- {
- return (u_long)-1;
- }
-
- /* Put the address together */
- return (octet4 << 24) | (octet3 << 16) | (octet2 << 8) | octet1;
- }
-