-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsubnet_api.c
78 lines (62 loc) · 1.38 KB
/
subnet_api.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <assert.h>
#include <arpa/inet.h>
#include "subnet_api.h"
subnet_t * lookupRoute6(uint64_t ip)
{
int low = 0, high = _net6_count -1;
while (low <= high) {
int mid = (low + high) / 2;
int pref = _net6_list[mid].prefixlen;
uint64_t msk1 = (~0ull >> pref);
uint64_t net0 = (_net6_list[mid].network);
if ((ip & ~msk1) == net0)
return &_net6_list[mid];
if (net0 > ip) {
high = mid - 1;
} else if (net0 < ip) {
low = mid + 1;
} else {
fprintf(stderr, "break, %lx %d\n", ip, _net6_count);
break;
}
}
return NULL;
}
subnet_t * lookupRoute4(uint64_t ip)
{
int low = 0, high = _net4_count -1;
while (low <= high) {
int mid = (low + high) / 2;
int pref = _net4_list[mid].prefixlen;
uint64_t msk1 = (~0ull >> pref);
uint64_t net0 = (_net4_list[mid].network);
if ((ip & ~msk1) == net0)
return &_net4_list[mid];
if (net0 > ip) {
high = mid - 1;
} else if (net0 < ip) {
low = mid + 1;
} else {
fprintf(stderr, "break, %llx %d\n", ip, _net4_count);
break;
}
}
return NULL;
}
uint64_t htonll(uint64_t val)
{
uint64_t data[2];
if (htons(0x1234) == 0x1234) {
return val;
}
data[0] = htonl(val >> 32);
data[1] = htonl(val & 0xffffffff);
return (data[1] << 32) | data[0];
}
uint64_t pton_val(const char *addr, int family)
{
uint64_t val[2] = {};
inet_pton(family, addr, val);
return htonll(val[0]);
}