[1064] in Coldmud discussion meeting
Re: [COLD] Standard way of converting "a.b.c.d" to 'struct in_addr'
daemon@ATHENA.MIT.EDU (Tue Aug 13 11:18:51 1996
)
Date: Tue, 13 Aug 1996 16:44:46 +0100
From: Luc Girardin <girardin@hei.unige.ch>
To: Brandon Gillespie <brandon@tombstone.sunrem.com>
Cc: coldstuff@cold.org
Reply-to: girardin@hei.unige.ch
Brandon Gillespie wrote:
> Right now the driver uses inet_ntoa(), which I _thought_ was standard
> (all of the systems' man pages I checked had it, and preferred it over
> other functions). However, Solaris does not have it. I've been idly
> working on an alternative, but I do not have enough reference to come up
> with a solution. I primarily need more details on what exactly
> inet_makeaddr() expects, and how to get "a.b.c.d" to the form it expects..
Try the following code, it should do the job and work on every
platform...
int inet_aton (const char *cp, struct in_addr *addr)
{
unsigned long parts[4];
register unsigned long val;
register unsigned long part0;
register unsigned long part1;
register unsigned long part2;
register unsigned long part3;
int part;
char *next;
part = 0;
for (;;)
{
if (!isdigit (*cp)) /* not decimal digit or leading 0, 0x */
return 0;
errno = 0;
parts[part++] = strtoul (cp, &next, 0); /* leading 0=octal, 0x=hex
*/
if (errno == ERANGE)
return 0;
if (*next == '.')
{
if (part >= 4)
return 0;
cp = next + 1;
}
else
break; /* from for loop */
}
/* Check for trailing non-whitespace characters */
if (strlen (next) != strspn (next, " \t\n\v\f\r"))
return 0;
/* Concoct the address according to the number of parts specified. */
val = 0;
part0 = parts[0];
part1 = parts[1];
part2 = parts[2];
part3 = parts[3];
switch (part)
{
case 4: /* a.b.c.d -- 8.8.8.8 bits */
if (part3 > 0xff || part2 > 0xff)
return 0;
val = part3;
part2 <<= 8;
/* FALLTHROUGH */
case 3: /* a.b.c -- 8.8.16 bits */
if (part2 > 0xffff || part1 > 0xff)
return 0;
val |= part2;
part1 <<= 16;
/* FALLTHROUGH */
case 2: /* a.b -- 8.24 bits */
if (part1 > 0xffffff || part0 > 0xff)
return 0;
val |= part1;
part0 <<= 24;
/* FALLTHROUGH */
case 1: /* a -- 32 bits */
val |= part0;
}
addr->s_addr = htonl (val);
return 1;
}
Cheers
-----BEGIN PBP PUBLIC INFO BLOCK-----
Luc Girardin The Graduate Institute of International Studies
Institut Universitaire de Hautes Etudes Internationales
Geneva, Switzerland, http://heiwww.unige.ch/girardin/
"Sane sicut lux seipsam et tenebras manifestat,
sic veritas normal sui et falsi est."
Spinoza, Ethics, Pt II, Prop. 43, 1675
-----END PBP PUBLIC INFO BLOCK-----