implement inet_lnaof, inet_netof, and inet_makeaddr
[musl] / src / network / inet_legacy.c
1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <arpa/inet.h>
4 #include <stdio.h>
5 #include "__dns.h"
6
7 in_addr_t inet_addr(const char *p)
8 {
9         struct sockaddr_in sin;
10         if (__ipparse(&sin, AF_INET, p)) return -1;
11         return sin.sin_addr.s_addr;
12 }
13
14 in_addr_t inet_network(const char *p)
15 {
16         return ntohl(inet_addr(p));
17 }
18
19 int inet_aton(const char *cp, struct in_addr *inp)
20 {
21         return inet_pton(AF_INET, cp, (void *)inp) > 0;
22 }
23
24 char *inet_ntoa(struct in_addr in)
25 {
26         static char buf[16];
27         unsigned char *a = (void *)&in;
28         snprintf(buf, sizeof buf, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
29         return buf;
30 }
31
32 struct in_addr inet_makeaddr(int net, int host)
33 {
34         uint32_t n = net, h = host;
35         if (n < 256) h |= n<<24;
36         else if (n < 65536) h |= n<<16;
37         else h |= n<<8;
38         return (struct in_addr){ h };
39 }
40
41 in_addr_t inet_lnaof(struct in_addr in)
42 {
43         uint32_t h = in.s_addr;
44         if (h>>24 < 128) return h & 0xffffff;
45         if (h>>24 < 192) return h & 0xffff;
46         return h & 0xff;
47 }
48
49 in_addr_t inet_netof(struct in_addr in)
50 {
51         uint32_t h = in.s_addr;
52         if (h>>24 < 128) return h >> 24;
53         if (h>>24 < 192) return h >> 16;
54         return h >> 8;
55 }