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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
/**
* \file HardwareAddressRetriever_unix.c
* \brief Hardware address retriever (Unix specific code).
* \author Sebastien Vincent
* \date 2010
*/
#if !defined(_WIN32) && !defined(_WIN64)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <net/if.h>
#if defined(__FreeBSD__) || defined(__APPLE__)
#include <ifaddrs.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <net/if_types.h>
#endif
#include "HardwareAddressRetriever.h"
jbyteArray getHardwareAddress(JNIEnv* env, jstring ifName)
{
int sock = -1;
struct ifreq ifr;
jbyteArray hwaddr = NULL;
char* name = NULL;
jbyte* addr = NULL;
int hwlen = 6;
name = (char*)(*env)->GetStringUTFChars(env, ifName, NULL);
if(!name)
{
return NULL;
}
#ifdef __linux__
sock = socket(AF_INET, SOCK_DGRAM, 0);
if(sock == -1)
{
(*env)->ReleaseStringUTFChars(env, ifName, name);
return NULL;
}
memset(&ifr, 0x00, sizeof(struct ifreq));
strncpy(ifr.ifr_name, name, IFNAMSIZ - 1);
ifr.ifr_name[IFNAMSIZ - 1] = 0x00;
if(ioctl(sock, SIOCGIFHWADDR, &ifr) != 0)
{
(*env)->ReleaseStringUTFChars(env, ifName, name);
close(sock);
return NULL;
}
close(sock);
addr = (const jbyte*)ifr.ifr_hwaddr.sa_data;
#else /* BSD like */
struct ifaddrs* addrs = NULL;
struct ifaddrs* ifa = NULL;
jbyte buf[hwlen];
if(getifaddrs(&addrs) != -1)
{
for(ifa = addrs ; ifa != NULL ; ifa = ifa->ifa_next)
{
if(ifa->ifa_addr->sa_family == AF_LINK && !strcmp(ifa->ifa_name, name))
{
struct sockaddr_dl* sdl = (struct sockaddr_dl*)ifa->ifa_addr;
if(sdl->sdl_type == IFT_ETHER)
{
memcpy(buf, LLADDR(sdl), hwlen);
addr = buf;
break;
}
}
}
freeifaddrs(addrs);
}
#endif
if(addr)
{
hwaddr = (*env)->NewByteArray(env, hwlen);
if(hwaddr)
{
/* copy the hardware address and return it */
(*env)->SetByteArrayRegion(env, hwaddr, 0, hwlen, addr);
}
}
/* cleanup */
(*env)->ReleaseStringUTFChars(env, ifName, name);
return hwaddr;
}
#endif
|