forked from measurement-factory/ipv4-heatmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
address-counter.c
81 lines (75 loc) · 1.36 KB
/
address-counter.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
79
80
81
/*
* IPv4 Heatmap
* (C) 2007 The Measurement Factory, Inc
* Licensed under the GPL, version 2
* http://maps.measurement-factory.com/
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <memory.h>
#include <err.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
/*
* Counts IPv4 addresses
*/
struct _item {
struct in_addr a;
unsigned int c;
struct _item *next;
};
typedef struct _item item;
item *array[65536];
static item *
find(struct in_addr a, int new)
{
unsigned int b = ntohl(a.s_addr) >> 16;
item **I;
item *i;
for (I = &array[b]; *I; I=&(*I)->next)
if ((*I)->a.s_addr == a.s_addr) {
i = *I;
if (i != array[b]) {
/* move to top */
*I = i->next;
i->next = array[b];
array[b] = i;
}
return i;
}
if (!new)
return NULL;
i = calloc(1, sizeof(*i));
if (NULL == i)
err(1, "malloc");
i->a = a;
i->next = array[b];
array[b] = i;
return i;
}
int
main(int argc, char *argv[])
{
char buf[128];
unsigned int b;
while (NULL != fgets(buf, sizeof(buf), stdin)) {
struct in_addr a;
item *i;
strtok(buf, "\r\n");
if (1 != inet_pton(AF_INET, buf, &a))
continue;
i = find(a, 1);
i->c++;
}
for (b = 0; b<65536; b++) {
item *i;
for (i = array[b]; i; i=i->next) {
if (NULL == inet_ntop(AF_INET, &i->a, buf, 128))
continue;
printf("%s\t%u\n", buf, i->c);
}
}
return 0;
}