File: arp_lookup_bsd.c

package info (click to toggle)
libnet-arp-perl 1.0.11-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 192 kB
  • sloc: ansic: 314; perl: 43; makefile: 3
file content (96 lines) | stat: -rwxr-xr-x 2,225 bytes parent folder | download | duplicates (2)
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
95
96
/*
Perl ARP Extension
Lookup the MAC address of an ip address
BSD code

Programmed by Bastian Ballmann
Last update: 20.09.2006

This program is free software; you can redistribute 
it and/or modify it under the terms of the 
GNU General Public License version 2 as published 
by the Free Software Foundation.

This program is distributed in the hope that it will 
be useful, but WITHOUT ANY WARRANTY; without even 
the implied warranty of MERCHANTABILITY or FITNESS 
FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details. 
*/

#include <sys/file.h>
#include <sys/socket.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <net/if_arp.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include "arp.h"

#define ROUNDUP(a) \
        ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))

int arp_lookup_bsd(const char *dev, const char *ip, char *mac)
{
  int mib[6];
  size_t needed;
  char *lim, *buf, *next;

  if ( (mac == NULL) || (dev == NULL) || (ip == NULL) )
    return -1;

  strncpy(mac,"unknown", HEX_HW_ADDR_LEN);
  mac[HEX_HW_ADDR_LEN-1] = '\0';

  mib[0] = CTL_NET;
  mib[1] = PF_ROUTE;
  mib[2] = 0;
  mib[3] = AF_INET;
  mib[4] = NET_RT_FLAGS;
  mib[5] = RTF_LLINFO;

  /* Retrieve routing table */

  if(sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
    {
      perror("route-sysctl-estimate");
      exit(1);
    }

  if((buf = malloc(needed)) == NULL)
    {
      perror("malloc");
      exit(1);
    }

  if(sysctl(mib, 6, buf, &needed, NULL, 0) < 0)
    {
      perror("retrieval of routing table");
      exit(1);
    }

  lim = buf + needed;
  next = buf;

  /* Search for the requested ip */
  while (next < lim) 
    {
      struct rt_msghdr *rtm = (struct rt_msghdr *)next;
      struct sockaddr_inarp *sinarp = (struct sockaddr_inarp *)(rtm + 1);
      struct sockaddr_dl *sdl = (struct sockaddr_dl *)((char *)sinarp + ROUNDUP(sinarp->sin_len));

      if( (sdl->sdl_alen) && (!strcmp(ip,inet_ntoa(sinarp->sin_addr))) )
	{ 
	  sprintf(mac,"%s", ether_ntoa((struct ether_addr *)LLADDR(sdl)));
	}

      next += rtm->rtm_msglen;
    }

  free(buf);
  return(0);
}