2
0

getgateway.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /* $Id: getgateway.c,v 1.13 2009/03/10 10:15:31 nanard Exp $ */
  2. /* libnatpmp
  3. * Copyright (c) 2007-2008, Thomas BERNARD <miniupnp@free.fr>
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  16. #include <stdio.h>
  17. #include <ctype.h>
  18. #ifndef WIN32
  19. #include <netinet/in.h>
  20. #endif
  21. #ifndef _MSC_VER
  22. #include <sys/param.h>
  23. #endif
  24. /* There is no portable method to get the default route gateway.
  25. * So below are three differents functions implementing this.
  26. * Parsing /proc/net/route is for linux.
  27. * sysctl is the way to access such informations on BSD systems.
  28. * Many systems should provide route information through raw PF_ROUTE
  29. * sockets. */
  30. #ifdef __linux__
  31. #define USE_PROC_NET_ROUTE
  32. #undef USE_SOCKET_ROUTE
  33. #undef USE_SYSCTL_NET_ROUTE
  34. #endif
  35. #ifdef BSD
  36. #undef USE_PROC_NET_ROUTE
  37. #define USE_SOCKET_ROUTE
  38. #undef USE_SYSCTL_NET_ROUTE
  39. #endif
  40. #ifdef __APPLE__
  41. #undef USE_PROC_NET_ROUTE
  42. #undef USE_SOCKET_ROUTE
  43. #define USE_SYSCTL_NET_ROUTE
  44. #endif
  45. #if ((defined(sun) || defined(__sun)) && defined(__SVR4))
  46. #undef USE_PROC_NET_ROUTE
  47. #define USE_SOCKET_ROUTE
  48. #undef USE_SYSCTL_NET_ROUTE
  49. #endif
  50. #ifdef WIN32
  51. #undef USE_PROC_NET_ROUTE
  52. #undef USE_SOCKET_ROUTE
  53. #undef USE_SYSCTL_NET_ROUTE
  54. #define USE_WIN32_CODE
  55. #endif
  56. #ifdef USE_SYSCTL_NET_ROUTE
  57. #include <stdlib.h>
  58. #include <sys/sysctl.h>
  59. #include <sys/socket.h>
  60. #include <net/route.h>
  61. #endif
  62. #ifdef USE_SOCKET_ROUTE
  63. #include <unistd.h>
  64. #include <string.h>
  65. #include <sys/socket.h>
  66. #include <net/if.h>
  67. #include <net/route.h>
  68. #endif
  69. #ifdef WIN32
  70. #include <unknwn.h>
  71. #include <winreg.h>
  72. #define MAX_KEY_LENGTH 255
  73. #define MAX_VALUE_LENGTH 16383
  74. #endif
  75. #include "getgateway.h"
  76. #ifndef WIN32
  77. #define SUCCESS (0)
  78. #define FAILED (-1)
  79. #endif
  80. #ifdef USE_PROC_NET_ROUTE
  81. int getdefaultgateway(in_addr_t * addr)
  82. {
  83. unsigned long d, g;
  84. char buf[256];
  85. int line = 0;
  86. FILE * f;
  87. char * p;
  88. f = fopen("/proc/net/route", "r");
  89. if(!f)
  90. return FAILED;
  91. while(fgets(buf, sizeof(buf), f)) {
  92. if(line > 0) {
  93. p = buf;
  94. while(*p && !isspace(*p))
  95. p++;
  96. while(*p && isspace(*p))
  97. p++;
  98. if(sscanf(p, "%lx%lx", &d, &g)==2) {
  99. if(d == 0) { /* default */
  100. *addr = g;
  101. fclose(f);
  102. return SUCCESS;
  103. }
  104. }
  105. }
  106. line++;
  107. }
  108. /* default route not found ! */
  109. if(f)
  110. fclose(f);
  111. return FAILED;
  112. }
  113. #endif /* #ifdef USE_PROC_NET_ROUTE */
  114. #ifdef USE_SYSCTL_NET_ROUTE
  115. #define ROUNDUP(a) \
  116. ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
  117. int getdefaultgateway(in_addr_t * addr)
  118. {
  119. #if 0
  120. /* net.route.0.inet.dump.0.0 ? */
  121. int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET,
  122. NET_RT_DUMP, 0, 0/*tableid*/};
  123. #endif
  124. /* net.route.0.inet.flags.gateway */
  125. int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET,
  126. NET_RT_FLAGS, RTF_GATEWAY};
  127. size_t l;
  128. char * buf, * p;
  129. struct rt_msghdr * rt;
  130. struct sockaddr * sa;
  131. struct sockaddr * sa_tab[RTAX_MAX];
  132. int i;
  133. int r = FAILED;
  134. if(sysctl(mib, sizeof(mib)/sizeof(int), 0, &l, 0, 0) < 0) {
  135. return FAILED;
  136. }
  137. if(l>0) {
  138. buf = malloc(l);
  139. if(sysctl(mib, sizeof(mib)/sizeof(int), buf, &l, 0, 0) < 0) {
  140. free(buf);
  141. return FAILED;
  142. }
  143. for(p=buf; p<buf+l; p+=rt->rtm_msglen) {
  144. rt = (struct rt_msghdr *)p;
  145. sa = (struct sockaddr *)(rt + 1);
  146. for(i=0; i<RTAX_MAX; i++) {
  147. if(rt->rtm_addrs & (1 << i)) {
  148. sa_tab[i] = sa;
  149. sa = (struct sockaddr *)((char *)sa + ROUNDUP(sa->sa_len));
  150. } else {
  151. sa_tab[i] = NULL;
  152. }
  153. }
  154. if( ((rt->rtm_addrs & (RTA_DST|RTA_GATEWAY)) == (RTA_DST|RTA_GATEWAY))
  155. && sa_tab[RTAX_DST]->sa_family == AF_INET
  156. && sa_tab[RTAX_GATEWAY]->sa_family == AF_INET) {
  157. if(((struct sockaddr_in *)sa_tab[RTAX_DST])->sin_addr.s_addr == 0) {
  158. *addr = ((struct sockaddr_in *)(sa_tab[RTAX_GATEWAY]))->sin_addr.s_addr;
  159. r = SUCCESS;
  160. }
  161. }
  162. }
  163. free(buf);
  164. }
  165. return r;
  166. }
  167. #endif /* #ifdef USE_SYSCTL_NET_ROUTE */
  168. #ifdef USE_SOCKET_ROUTE
  169. /* Thanks to Darren Kenny for this code */
  170. #define NEXTADDR(w, u) \
  171. if (rtm_addrs & (w)) {\
  172. l = sizeof(struct sockaddr); memmove(cp, &(u), l); cp += l;\
  173. }
  174. #define rtm m_rtmsg.m_rtm
  175. struct {
  176. struct rt_msghdr m_rtm;
  177. char m_space[512];
  178. } m_rtmsg;
  179. int getdefaultgateway(in_addr_t *addr)
  180. {
  181. int s, seq, l, rtm_addrs, i;
  182. pid_t pid;
  183. struct sockaddr so_dst, so_mask;
  184. char *cp = m_rtmsg.m_space;
  185. struct sockaddr *gate = NULL, *sa;
  186. struct rt_msghdr *msg_hdr;
  187. pid = getpid();
  188. seq = 0;
  189. rtm_addrs = RTA_DST | RTA_NETMASK;
  190. memset(&so_dst, 0, sizeof(so_dst));
  191. memset(&so_mask, 0, sizeof(so_mask));
  192. memset(&rtm, 0, sizeof(struct rt_msghdr));
  193. rtm.rtm_type = RTM_GET;
  194. rtm.rtm_flags = RTF_UP | RTF_GATEWAY;
  195. rtm.rtm_version = RTM_VERSION;
  196. rtm.rtm_seq = ++seq;
  197. rtm.rtm_addrs = rtm_addrs;
  198. so_dst.sa_family = AF_INET;
  199. so_mask.sa_family = AF_INET;
  200. NEXTADDR(RTA_DST, so_dst);
  201. NEXTADDR(RTA_NETMASK, so_mask);
  202. rtm.rtm_msglen = l = cp - (char *)&m_rtmsg;
  203. s = socket(PF_ROUTE, SOCK_RAW, 0);
  204. if (write(s, (char *)&m_rtmsg, l) < 0) {
  205. close(s);
  206. return FAILED;
  207. }
  208. do {
  209. l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg));
  210. } while (l > 0 && (rtm.rtm_seq != seq || rtm.rtm_pid != pid));
  211. close(s);
  212. msg_hdr = &rtm;
  213. cp = ((char *)(msg_hdr + 1));
  214. if (msg_hdr->rtm_addrs) {
  215. for (i = 1; i; i <<= 1)
  216. if (i & msg_hdr->rtm_addrs) {
  217. sa = (struct sockaddr *)cp;
  218. if (i == RTA_GATEWAY )
  219. gate = sa;
  220. cp += sizeof(struct sockaddr);
  221. }
  222. } else {
  223. return FAILED;
  224. }
  225. if (gate != NULL ) {
  226. *addr = ((struct sockaddr_in *)gate)->sin_addr.s_addr;
  227. return SUCCESS;
  228. } else {
  229. return FAILED;
  230. }
  231. }
  232. #endif /* #ifdef USE_SOCKET_ROUTE */
  233. #ifdef USE_WIN32_CODE
  234. int getdefaultgateway(in_addr_t * addr)
  235. {
  236. HKEY networkCardsKey;
  237. HKEY networkCardKey;
  238. HKEY interfacesKey;
  239. HKEY interfaceKey;
  240. DWORD i = 0;
  241. DWORD numSubKeys = 0;
  242. TCHAR keyName[MAX_KEY_LENGTH];
  243. DWORD keyNameLength = MAX_KEY_LENGTH;
  244. BYTE keyValue[MAX_VALUE_LENGTH];
  245. DWORD keyValueLength = MAX_VALUE_LENGTH;
  246. DWORD keyValueType = REG_SZ;
  247. BYTE gatewayValue[MAX_VALUE_LENGTH];
  248. DWORD gatewayValueLength = MAX_VALUE_LENGTH;
  249. DWORD gatewayValueType = REG_MULTI_SZ;
  250. int done = 0;
  251. char networkCardsPath[] = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";
  252. char interfacesPath[] = "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces";
  253. // The windows registry lists its primary network devices in the following location:
  254. // HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards
  255. //
  256. // Each network device has its own subfolder, named with an index, with various properties:
  257. // -NetworkCards
  258. // -5
  259. // -Description = Broadcom 802.11n Network Adapter
  260. // -ServiceName = {E35A72F8-5065-4097-8DFE-C7790774EE4D}
  261. // -8
  262. // -Description = Marvell Yukon 88E8058 PCI-E Gigabit Ethernet Controller
  263. // -ServiceName = {86226414-5545-4335-A9D1-5BD7120119AD}
  264. //
  265. // The above service name is the name of a subfolder within:
  266. // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
  267. //
  268. // There may be more subfolders in this interfaces path than listed in the network cards path above:
  269. // -Interfaces
  270. // -{3a539854-6a70-11db-887c-806e6f6e6963}
  271. // -DhcpIPAddress = 0.0.0.0
  272. // -[more]
  273. // -{E35A72F8-5065-4097-8DFE-C7790774EE4D}
  274. // -DhcpIPAddress = 10.0.1.4
  275. // -DhcpDefaultGateway = 10.0.1.1
  276. // -[more]
  277. // -{86226414-5545-4335-A9D1-5BD7120119AD}
  278. // -DhcpIpAddress = 10.0.1.5
  279. // -DhcpDefaultGateay = 10.0.1.1
  280. // -[more]
  281. //
  282. // In order to extract this information, we enumerate each network card, and extract the ServiceName value.
  283. // This is then used to open the interface subfolder, and attempt to extract a DhcpDefaultGateway value.
  284. // Once one is found, we're done.
  285. //
  286. // It may be possible to simply enumerate the interface folders until we find one with a DhcpDefaultGateway value.
  287. // However, the technique used is the technique most cited on the web, and we assume it to be more correct.
  288. if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predifined key
  289. networkCardsPath, // Name of registry subkey to open
  290. 0, // Reserved - must be zero
  291. KEY_READ, // Mask - desired access rights
  292. &networkCardsKey)) // Pointer to output key
  293. {
  294. // Unable to open network cards keys
  295. return -1;
  296. }
  297. if(ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Open registry key or predefined key
  298. interfacesPath, // Name of registry subkey to open
  299. 0, // Reserved - must be zero
  300. KEY_READ, // Mask - desired access rights
  301. &interfacesKey)) // Pointer to output key
  302. {
  303. // Unable to open interfaces key
  304. RegCloseKey(networkCardsKey);
  305. return -1;
  306. }
  307. // Figure out how many subfolders are within the NetworkCards folder
  308. RegQueryInfoKey(networkCardsKey, NULL, NULL, NULL, &numSubKeys, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
  309. //printf( "Number of subkeys: %u\n", (unsigned int)numSubKeys);
  310. // Enumrate through each subfolder within the NetworkCards folder
  311. for(i = 0; i < numSubKeys && !done; i++)
  312. {
  313. keyNameLength = MAX_KEY_LENGTH;
  314. if(ERROR_SUCCESS == RegEnumKeyEx(networkCardsKey, // Open registry key
  315. i, // Index of subkey to retrieve
  316. keyName, // Buffer that receives the name of the subkey
  317. &keyNameLength, // Variable that receives the size of the above buffer
  318. NULL, // Reserved - must be NULL
  319. NULL, // Buffer that receives the class string
  320. NULL, // Variable that receives the size of the above buffer
  321. NULL)) // Variable that receives the last write time of subkey
  322. {
  323. if(RegOpenKeyEx(networkCardsKey, keyName, 0, KEY_READ, &networkCardKey) == ERROR_SUCCESS)
  324. {
  325. keyValueLength = MAX_VALUE_LENGTH;
  326. if(ERROR_SUCCESS == RegQueryValueEx(networkCardKey, // Open registry key
  327. "ServiceName", // Name of key to query
  328. NULL, // Reserved - must be NULL
  329. &keyValueType, // Receives value type
  330. keyValue, // Receives value
  331. &keyValueLength)) // Receives value length in bytes
  332. {
  333. //printf("keyValue: %s\n", keyValue);
  334. if(RegOpenKeyEx(interfacesKey, (char *)keyValue, 0, KEY_READ, &interfaceKey) == ERROR_SUCCESS)
  335. {
  336. gatewayValueLength = MAX_VALUE_LENGTH;
  337. if(ERROR_SUCCESS == RegQueryValueEx(interfaceKey, // Open registry key
  338. "DhcpDefaultGateway", // Name of key to query
  339. NULL, // Reserved - must be NULL
  340. &gatewayValueType, // Receives value type
  341. gatewayValue, // Receives value
  342. &gatewayValueLength)) // Receives value length in bytes
  343. {
  344. // Check to make sure it's a string
  345. if(gatewayValueType == REG_MULTI_SZ || gatewayValueType == REG_SZ)
  346. {
  347. //printf("gatewayValue: %s\n", gatewayValue);
  348. done = 1;
  349. }
  350. }
  351. else if(ERROR_SUCCESS == RegQueryValueEx(interfaceKey, // Open registry key
  352. "DefaultGateway", // Name of key to query
  353. NULL, // Reserved - must be NULL
  354. &gatewayValueType, // Receives value type
  355. gatewayValue, // Receives value
  356. &gatewayValueLength)) // Receives value length in bytes
  357. {
  358. // Check to make sure it's a string
  359. if(gatewayValueType == REG_MULTI_SZ || gatewayValueType == REG_SZ)
  360. {
  361. //printf("gatewayValue: %s\n", gatewayValue);
  362. done = 1;
  363. }
  364. }
  365. RegCloseKey(interfaceKey);
  366. }
  367. }
  368. RegCloseKey(networkCardKey);
  369. }
  370. }
  371. }
  372. RegCloseKey(interfacesKey);
  373. RegCloseKey(networkCardsKey);
  374. if(done)
  375. {
  376. *addr = inet_addr((char *)gatewayValue);
  377. return 0;
  378. }
  379. return -1;
  380. }
  381. #endif /* #ifdef USE_WIN32_CODE */