-
Notifications
You must be signed in to change notification settings - Fork 1
/
arp.cpp
94 lines (82 loc) · 1.83 KB
/
arp.cpp
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
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "arp.h"
#include <stdlib.h>
#include <memory.h>
#include <sys/ioctl.h>
#include <unistd.h>
//borrowed from arp-bsd.c
//reconsider arp-none.c, arp-ioctl.c(1), arp-win32.c(no!)
/*
* ARP ioctl request
*/
struct arpreq {
struct sockaddr arp_pa; /* protocol address */
struct sockaddr arp_ha; /* hardware address */
int arp_flags; /* flags */
};
/* arp_flags and at_flags field values */
#define ATF_INUSE 0x01 /* entry in use */
#define ATF_COM 0x02 /* completed entry (enaddr valid) */
#define ATF_PERM 0x04 /* permanent entry */
#define ATF_PUBL 0x08 /* publish entry (respond for other host) */
#define ATF_USETRAILERS 0x10 /* has requested trailers */
struct arp_handle {
int fd;
#ifdef HAVE_ARPREQ_ARP_DEV
intf_t *intf;
#endif
};
arp_t *
arp_open(void)
{
arp_t *a;
if ((a = (arp_t*)calloc(1, sizeof(*a))) != NULL) {
#ifdef HAVE_STREAMS_MIB2
if ((a->fd = open(IP_DEV_NAME, O_RDWR)) < 0)
#elif defined(HAVE_STREAMS_ROUTE)
if ((a->fd = open("/dev/route", O_WRONLY, 0)) < 0)
#else
if ((a->fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
#endif
return (arp_close(a));
#ifdef HAVE_ARPREQ_ARP_DEV
if ((a->intf = intf_open()) == NULL)
return (arp_close(a));
#endif
}
return (a);
}
int
arp_get(arp_t *a, struct arp_entry *entry)
{
struct arpreq ar;
memset(&ar, 0, sizeof(ar));
if (addr_ntos(&entry->arp_pa, &ar.arp_pa) < 0)
return (-1);
#ifdef HAVE_ARPREQ_ARP_DEV
if (intf_loop(a->intf, _arp_set_dev, &ar) != 1) {
errno = ESRCH;
return (-1);
}
#endif
if (ioctl(a->fd, SIOCGARP, &ar) < 0)
return (-1);
if ((ar.arp_flags & ATF_COM) == 0) {
errno = ESRCH;
return (-1);
}
return (addr_ston(&ar.arp_ha, &entry->arp_ha));
}
arp_t *
arp_close(arp_t *a)
{
if (a != NULL) {
if (a->fd >= 0)
close(a->fd);
#ifdef HAVE_ARPREQ_ARP_DEV
if (a->intf != NULL)
intf_close(a->intf);
#endif
free(a);
}
return (NULL);
}