1 #include <string.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <sys/socket.h>
5 #include <netinet/in.h>
6 #include <arpa/inet.h>
7 #include "gskipv4.h"
8 
9 /* Standard ipv4 addresses in guint8[4] format. */
10 
11 const guint8 gsk_ipv4_ip_address_any[4] =
12   {
13     (INADDR_ANY & 0xff000000) >> 24,
14     (INADDR_ANY & 0x00ff0000) >> 16,
15     (INADDR_ANY & 0x0000ff00) >>  8,
16     (INADDR_ANY & 0x000000ff)
17   };
18 const guint8 gsk_ipv4_ip_address_loopback[4] =
19   {
20     (INADDR_LOOPBACK & 0xff000000) >> 24,
21     (INADDR_LOOPBACK & 0x00ff0000) >> 16,
22     (INADDR_LOOPBACK & 0x0000ff00) >>  8,
23     (INADDR_LOOPBACK & 0x000000ff)
24   };
25 
26 
27 /**
28  * gsk_ipv4_parse:
29  * @str: string containing dotted decimal IPv4 address.
30  * @ip_addr_out: the 4-byte IPv4 address.
31  *
32  * Parse a numeric IP address, in the standard fashion (RFC 1034, 3.6.1).
33  *
34  * returns: whether the address was parsed successfully.
35  */
36 gboolean
gsk_ipv4_parse(const char * str,guint8 * ip_addr_out)37 gsk_ipv4_parse (const char *str, guint8 *ip_addr_out)
38 {
39   char *endp;
40   gulong n;
41   guint i;
42 
43   for (i = 0; i < 3; ++i)
44     {
45       const char *dot;
46 
47       dot = strchr (str, '.');
48       if (!dot)
49 	return FALSE;
50 
51       n = strtoul (str, &endp, 10);
52       if (endp != dot)
53 	return FALSE;
54       if (n > 255)
55 	return FALSE;
56       ip_addr_out[i] = n;
57 
58       str = dot + 1;
59     }
60 
61   n = strtoul (str, &endp, 10);
62   if (endp == str || *endp)
63     return FALSE;
64   if (n > 255)
65     return FALSE;
66   ip_addr_out[3] = n;
67 
68   return TRUE;
69 }
70