1*8357Ssam /* inet_addr.c 4.3 82/10/07 */ 28324Ssam 38324Ssam #include <sys/types.h> 48324Ssam #include <ctype.h> 5*8357Ssam #include <net/in.h> 68324Ssam 78309Ssam /* 88309Ssam * Internet address interpretation routine. 98309Ssam * All the network library routines call this 108309Ssam * routine to interpret entries in the data bases 118309Ssam * which are expected to be an address. 12*8357Ssam * The value returned is in network order. 138309Ssam */ 14*8357Ssam struct in_addr 158309Ssam inet_addr(cp) 168309Ssam register char *cp; 178309Ssam { 18*8357Ssam register u_long val, base, n; 198309Ssam register char c; 20*8357Ssam u_long parts[4], *pp = parts; 218309Ssam 228309Ssam again: 23*8357Ssam /* 24*8357Ssam * Collect number up to ``.''. 25*8357Ssam * Values are specified as for C: 26*8357Ssam * 0x=hex, 0=octal, other=decimal. 27*8357Ssam */ 288309Ssam val = 0; base = 10; 298309Ssam if (*cp == '0') 308309Ssam base = 8, cp++; 318309Ssam if (*cp == 'x' || *cp == 'X') 328309Ssam base = 16, cp++; 338309Ssam while (c = *cp) { 348309Ssam if (isdigit(c)) { 358309Ssam val = (val * base) + (c - '0'); 368309Ssam cp++; 378309Ssam continue; 388309Ssam } 398309Ssam if (base == 16 && isxdigit(c)) { 408309Ssam val = (val << 4) + (c + 10 - (islower(c) ? 'a' : 'A')); 418309Ssam cp++; 428309Ssam continue; 438309Ssam } 448309Ssam break; 458309Ssam } 468309Ssam if (*cp == '.') { 478309Ssam /* 488309Ssam * Internet format: 498309Ssam * a.b.c.d 508309Ssam * a.b.c (with c treated as 16-bits) 518309Ssam * a.b (with b treated as 24 bits) 528309Ssam */ 538309Ssam if (pp >= parts + 4) 548309Ssam return (-1); 558309Ssam *pp++ = val, cp++; 568309Ssam goto again; 578309Ssam } 58*8357Ssam /* 59*8357Ssam * Check for trailing characters. 60*8357Ssam */ 618309Ssam if (*cp && !isspace(*cp)) 628309Ssam return (-1); 63*8357Ssam *pp++ = val; 64*8357Ssam /* 65*8357Ssam * Concoct the address according to 66*8357Ssam * the number of parts specified. 67*8357Ssam */ 688309Ssam n = pp - parts; 69*8357Ssam switch (n) { 70*8357Ssam 71*8357Ssam case 1: /* a -- 32 bits */ 728309Ssam val = parts[0]; 73*8357Ssam break; 74*8357Ssam 75*8357Ssam case 2: /* a.b -- 8.24 bits */ 76*8357Ssam val = (parts[0] << 24) | (parts[1] & 0xffffff); 77*8357Ssam break; 78*8357Ssam 79*8357Ssam case 3: /* a.b.c -- 8.8.16 bits */ 80*8357Ssam val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | 81*8357Ssam (parts[2] & 0xffff); 82*8357Ssam break; 83*8357Ssam 84*8357Ssam case 4: /* a.b.c.d -- 8.8.8.8 bits */ 85*8357Ssam val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | 86*8357Ssam ((parts[2] & 0xff) << 8) | (parts[3] & 0xff); 87*8357Ssam break; 88*8357Ssam 89*8357Ssam default: 90*8357Ssam return (-1); 918309Ssam } 92*8357Ssam val = htonl(val); 938309Ssam return (val); 948309Ssam } 95