1*8361Ssam /* inet_addr.c 4.4 82/10/07 */ 28324Ssam 38324Ssam #include <sys/types.h> 48324Ssam #include <ctype.h> 58357Ssam #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. 128357Ssam * The value returned is in network order. 138309Ssam */ 14*8361Ssam u_long 158309Ssam inet_addr(cp) 168309Ssam register char *cp; 178309Ssam { 188357Ssam register u_long val, base, n; 198309Ssam register char c; 208357Ssam u_long parts[4], *pp = parts; 218309Ssam 228309Ssam again: 238357Ssam /* 248357Ssam * Collect number up to ``.''. 258357Ssam * Values are specified as for C: 268357Ssam * 0x=hex, 0=octal, other=decimal. 278357Ssam */ 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 } 588357Ssam /* 598357Ssam * Check for trailing characters. 608357Ssam */ 618309Ssam if (*cp && !isspace(*cp)) 628309Ssam return (-1); 638357Ssam *pp++ = val; 648357Ssam /* 658357Ssam * Concoct the address according to 668357Ssam * the number of parts specified. 678357Ssam */ 688309Ssam n = pp - parts; 698357Ssam switch (n) { 708357Ssam 718357Ssam case 1: /* a -- 32 bits */ 728309Ssam val = parts[0]; 738357Ssam break; 748357Ssam 758357Ssam case 2: /* a.b -- 8.24 bits */ 768357Ssam val = (parts[0] << 24) | (parts[1] & 0xffffff); 778357Ssam break; 788357Ssam 798357Ssam case 3: /* a.b.c -- 8.8.16 bits */ 808357Ssam val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | 818357Ssam (parts[2] & 0xffff); 828357Ssam break; 838357Ssam 848357Ssam case 4: /* a.b.c.d -- 8.8.8.8 bits */ 858357Ssam val = (parts[0] << 24) | ((parts[1] & 0xff) << 16) | 868357Ssam ((parts[2] & 0xff) << 8) | (parts[3] & 0xff); 878357Ssam break; 888357Ssam 898357Ssam default: 908357Ssam return (-1); 918309Ssam } 928357Ssam val = htonl(val); 938309Ssam return (val); 948309Ssam } 95