#if defined(LIBC_SCCS) && !defined(lint)
static const char orig_rcsid[] = "From Id: inet_net_pton.c,v 1.8 1996/11/21 10:28:12 vixie Exp $";
#endif
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/lib/libc/net/inet_net_pton.c,v 1.9 2003/09/15 23:38:06 fenner Exp $");
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef SPRINTF_CHAR
# define SPRINTF(x) strlen(sprintfx)
#else
# define SPRINTF(x) ((size_t)sprintf x)
#endif
static int inet_net_pton_ipv4(const char *src, u_char *dst, size_t size);
int
inet_net_pton(af, src, dst, size)
int af;
const char *src;
void *dst;
size_t size;
{
switch (af) {
case AF_INET:
return (inet_net_pton_ipv4(src, dst, size));
default:
errno = EAFNOSUPPORT;
return (-1);
}
}
static int
inet_net_pton_ipv4(src, dst, size)
const char *src;
u_char *dst;
size_t size;
{
static const char
xdigits[] = "0123456789abcdef",
digits[] = "0123456789";
int n, ch, tmp, dirty, bits;
const u_char *odst = dst;
ch = *src++;
if (ch == '0' && (src[0] == 'x' || src[0] == 'X')
&& isascii(src[1]) && isxdigit(src[1])) {
if (size <= 0)
goto emsgsize;
*dst = 0, dirty = 0;
src++;
while ((ch = *src++) != '\0' &&
isascii(ch) && isxdigit(ch)) {
if (isupper(ch))
ch = tolower(ch);
n = strchr(xdigits, ch) - xdigits;
assert(n >= 0 && n <= 15);
*dst |= n;
if (!dirty++)
*dst <<= 4;
else if (size-- > 0)
*++dst = 0, dirty = 0;
else
goto emsgsize;
}
if (dirty)
size--;
} else if (isascii(ch) && isdigit(ch)) {
for (;;) {
tmp = 0;
do {
n = strchr(digits, ch) - digits;
assert(n >= 0 && n <= 9);
tmp *= 10;
tmp += n;
if (tmp > 255)
goto enoent;
} while ((ch = *src++) != '\0' &&
isascii(ch) && isdigit(ch));
if (size-- <= 0)
goto emsgsize;
*dst++ = (u_char) tmp;
if (ch == '\0' || ch == '/')
break;
if (ch != '.')
goto enoent;
ch = *src++;
if (!isascii(ch) || !isdigit(ch))
goto enoent;
}
} else
goto enoent;
bits = -1;
if (ch == '/' && isascii(src[0]) && isdigit(src[0]) && dst > odst) {
ch = *src++;
bits = 0;
do {
n = strchr(digits, ch) - digits;
assert(n >= 0 && n <= 9);
bits *= 10;
bits += n;
} while ((ch = *src++) != '\0' && isascii(ch) && isdigit(ch));
if (ch != '\0')
goto enoent;
if (bits > 32)
goto emsgsize;
}
if (ch != '\0')
goto enoent;
if (dst == odst)
goto enoent;
if (bits == -1) {
if (*odst >= 240)
bits = 32;
else if (*odst >= 224)
bits = 4;
else if (*odst >= 192)
bits = 24;
else if (*odst >= 128)
bits = 16;
else
bits = 8;
if (bits < ((dst - odst) * 8))
bits = (dst - odst) * 8;
}
while (bits > ((dst - odst) * 8)) {
if (size-- <= 0)
goto emsgsize;
*dst++ = '\0';
}
return (bits);
enoent:
errno = ENOENT;
return (-1);
emsgsize:
errno = EMSGSIZE;
return (-1);
}
#undef inet_net_pton
__weak_reference(__inet_net_pton, inet_net_pton);