iphlpapi: Implement if_nametoindex.
[wine.git] / dlls / iphlpapi / iphlpapi_main.c
blobc592a902ef6601b41eb2373d48f84b0b7ebb82d4
1 /*
2 * iphlpapi dll implementation
4 * Copyright (C) 2003,2006 Juan Lang
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #ifdef HAVE_NETINET_IN_H
28 # include <netinet/in.h>
29 #endif
30 #ifdef HAVE_ARPA_INET_H
31 # include <arpa/inet.h>
32 #endif
33 #ifdef HAVE_ARPA_NAMESER_H
34 # include <arpa/nameser.h>
35 #endif
36 #ifdef HAVE_RESOLV_H
37 # include <resolv.h>
38 #endif
40 #define NONAMELESSUNION
41 #define NONAMELESSSTRUCT
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winreg.h"
45 #define USE_WS_PREFIX
46 #include "winsock2.h"
47 #include "winternl.h"
48 #include "ws2ipdef.h"
49 #include "iphlpapi.h"
50 #include "ifenum.h"
51 #include "ipstats.h"
52 #include "ipifcons.h"
53 #include "fltdefs.h"
54 #include "ifdef.h"
55 #include "netioapi.h"
56 #include "tcpestats.h"
58 #include "wine/debug.h"
59 #include "wine/unicode.h"
61 WINE_DEFAULT_DEBUG_CHANNEL(iphlpapi);
63 #ifndef IF_NAMESIZE
64 #define IF_NAMESIZE 16
65 #endif
67 #ifndef INADDR_NONE
68 #define INADDR_NONE ~0UL
69 #endif
71 /******************************************************************
72 * AddIPAddress (IPHLPAPI.@)
74 * Add an IP address to an adapter.
76 * PARAMS
77 * Address [In] IP address to add to the adapter
78 * IpMask [In] subnet mask for the IP address
79 * IfIndex [In] adapter index to add the address
80 * NTEContext [Out] Net Table Entry (NTE) context for the IP address
81 * NTEInstance [Out] NTE instance for the IP address
83 * RETURNS
84 * Success: NO_ERROR
85 * Failure: error code from winerror.h
87 * FIXME
88 * Stub. Currently returns ERROR_NOT_SUPPORTED.
90 DWORD WINAPI AddIPAddress(IPAddr Address, IPMask IpMask, DWORD IfIndex, PULONG NTEContext, PULONG NTEInstance)
92 FIXME(":stub\n");
93 return ERROR_NOT_SUPPORTED;
97 /******************************************************************
98 * AllocateAndGetIfTableFromStack (IPHLPAPI.@)
100 * Get table of local interfaces.
101 * Like GetIfTable(), but allocate the returned table from heap.
103 * PARAMS
104 * ppIfTable [Out] pointer into which the MIB_IFTABLE is
105 * allocated and returned.
106 * bOrder [In] whether to sort the table
107 * heap [In] heap from which the table is allocated
108 * flags [In] flags to HeapAlloc
110 * RETURNS
111 * ERROR_INVALID_PARAMETER if ppIfTable is NULL, whatever
112 * GetIfTable() returns otherwise.
114 DWORD WINAPI AllocateAndGetIfTableFromStack(PMIB_IFTABLE *ppIfTable,
115 BOOL bOrder, HANDLE heap, DWORD flags)
117 DWORD ret;
119 TRACE("ppIfTable %p, bOrder %d, heap %p, flags 0x%08x\n", ppIfTable,
120 bOrder, heap, flags);
121 if (!ppIfTable)
122 ret = ERROR_INVALID_PARAMETER;
123 else {
124 DWORD dwSize = 0;
126 ret = GetIfTable(*ppIfTable, &dwSize, bOrder);
127 if (ret == ERROR_INSUFFICIENT_BUFFER) {
128 *ppIfTable = HeapAlloc(heap, flags, dwSize);
129 ret = GetIfTable(*ppIfTable, &dwSize, bOrder);
132 TRACE("returning %d\n", ret);
133 return ret;
137 static int IpAddrTableNumericSorter(const void *a, const void *b)
139 int ret = 0;
141 if (a && b)
142 ret = ((const MIB_IPADDRROW*)a)->dwAddr - ((const MIB_IPADDRROW*)b)->dwAddr;
143 return ret;
146 static int IpAddrTableLoopbackSorter(const void *a, const void *b)
148 const MIB_IPADDRROW *left = a, *right = b;
149 int ret = 0;
151 if (isIfIndexLoopback(left->dwIndex))
152 ret = 1;
153 else if (isIfIndexLoopback(right->dwIndex))
154 ret = -1;
156 return ret;
159 /******************************************************************
160 * AllocateAndGetIpAddrTableFromStack (IPHLPAPI.@)
162 * Get interface-to-IP address mapping table.
163 * Like GetIpAddrTable(), but allocate the returned table from heap.
165 * PARAMS
166 * ppIpAddrTable [Out] pointer into which the MIB_IPADDRTABLE is
167 * allocated and returned.
168 * bOrder [In] whether to sort the table
169 * heap [In] heap from which the table is allocated
170 * flags [In] flags to HeapAlloc
172 * RETURNS
173 * ERROR_INVALID_PARAMETER if ppIpAddrTable is NULL, other error codes on
174 * failure, NO_ERROR on success.
176 DWORD WINAPI AllocateAndGetIpAddrTableFromStack(PMIB_IPADDRTABLE *ppIpAddrTable,
177 BOOL bOrder, HANDLE heap, DWORD flags)
179 DWORD ret;
181 TRACE("ppIpAddrTable %p, bOrder %d, heap %p, flags 0x%08x\n",
182 ppIpAddrTable, bOrder, heap, flags);
183 ret = getIPAddrTable(ppIpAddrTable, heap, flags);
184 if (!ret && bOrder)
185 qsort((*ppIpAddrTable)->table, (*ppIpAddrTable)->dwNumEntries,
186 sizeof(MIB_IPADDRROW), IpAddrTableNumericSorter);
187 TRACE("returning %d\n", ret);
188 return ret;
192 /******************************************************************
193 * CancelIPChangeNotify (IPHLPAPI.@)
195 * Cancel a previous notification created by NotifyAddrChange or
196 * NotifyRouteChange.
198 * PARAMS
199 * overlapped [In] overlapped structure that notifies the caller
201 * RETURNS
202 * Success: TRUE
203 * Failure: FALSE
205 * FIXME
206 * Stub, returns FALSE.
208 BOOL WINAPI CancelIPChangeNotify(LPOVERLAPPED overlapped)
210 FIXME("(overlapped %p): stub\n", overlapped);
211 return FALSE;
215 /******************************************************************
216 * CancelMibChangeNotify2 (IPHLPAPI.@)
218 DWORD WINAPI CancelMibChangeNotify2(HANDLE handle)
220 FIXME("(handle %p): stub\n", handle);
221 return NO_ERROR;
225 /******************************************************************
226 * CreateIpForwardEntry (IPHLPAPI.@)
228 * Create a route in the local computer's IP table.
230 * PARAMS
231 * pRoute [In] new route information
233 * RETURNS
234 * Success: NO_ERROR
235 * Failure: error code from winerror.h
237 * FIXME
238 * Stub, always returns NO_ERROR.
240 DWORD WINAPI CreateIpForwardEntry(PMIB_IPFORWARDROW pRoute)
242 FIXME("(pRoute %p): stub\n", pRoute);
243 /* could use SIOCADDRT, not sure I want to */
244 return 0;
248 /******************************************************************
249 * CreateIpNetEntry (IPHLPAPI.@)
251 * Create entry in the ARP table.
253 * PARAMS
254 * pArpEntry [In] new ARP entry
256 * RETURNS
257 * Success: NO_ERROR
258 * Failure: error code from winerror.h
260 * FIXME
261 * Stub, always returns NO_ERROR.
263 DWORD WINAPI CreateIpNetEntry(PMIB_IPNETROW pArpEntry)
265 FIXME("(pArpEntry %p)\n", pArpEntry);
266 /* could use SIOCSARP on systems that support it, not sure I want to */
267 return 0;
271 /******************************************************************
272 * CreateProxyArpEntry (IPHLPAPI.@)
274 * Create a Proxy ARP (PARP) entry for an IP address.
276 * PARAMS
277 * dwAddress [In] IP address for which this computer acts as a proxy.
278 * dwMask [In] subnet mask for dwAddress
279 * dwIfIndex [In] interface index
281 * RETURNS
282 * Success: NO_ERROR
283 * Failure: error code from winerror.h
285 * FIXME
286 * Stub, returns ERROR_NOT_SUPPORTED.
288 DWORD WINAPI CreateProxyArpEntry(DWORD dwAddress, DWORD dwMask, DWORD dwIfIndex)
290 FIXME("(dwAddress 0x%08x, dwMask 0x%08x, dwIfIndex 0x%08x): stub\n",
291 dwAddress, dwMask, dwIfIndex);
292 return ERROR_NOT_SUPPORTED;
295 static char *debugstr_ipv6(const struct WS_sockaddr_in6 *sin, char *buf)
297 const IN6_ADDR *addr = &sin->sin6_addr;
298 char *p = buf;
299 int i;
300 BOOL in_zero = FALSE;
302 for (i = 0; i < 7; i++)
304 if (!addr->u.Word[i])
306 if (i == 0)
307 *p++ = ':';
308 if (!in_zero)
310 *p++ = ':';
311 in_zero = TRUE;
314 else
316 p += sprintf(p, "%x:", ntohs(addr->u.Word[i]));
317 in_zero = FALSE;
320 sprintf(p, "%x", ntohs(addr->u.Word[7]));
321 return buf;
324 static BOOL map_address_6to4( const SOCKADDR_IN6 *addr6, SOCKADDR_IN *addr4 )
326 ULONG i;
328 if (addr6->sin6_family != WS_AF_INET6) return FALSE;
330 for (i = 0; i < 5; i++)
331 if (addr6->sin6_addr.u.Word[i]) return FALSE;
333 if (addr6->sin6_addr.u.Word[5] != 0xffff) return FALSE;
335 addr4->sin_family = WS_AF_INET;
336 addr4->sin_port = addr6->sin6_port;
337 addr4->sin_addr.S_un.S_addr = addr6->sin6_addr.u.Word[6] << 16 | addr6->sin6_addr.u.Word[7];
338 memset( &addr4->sin_zero, 0, sizeof(addr4->sin_zero) );
340 return TRUE;
343 static BOOL find_src_address( MIB_IPADDRTABLE *table, const SOCKADDR_IN *dst, SOCKADDR_IN6 *src )
345 MIB_IPFORWARDROW row;
346 DWORD i, j;
348 if (GetBestRoute( dst->sin_addr.S_un.S_addr, 0, &row )) return FALSE;
350 for (i = 0; i < table->dwNumEntries; i++)
352 /* take the first address */
353 if (table->table[i].dwIndex == row.dwForwardIfIndex)
355 src->sin6_family = WS_AF_INET6;
356 src->sin6_port = 0;
357 src->sin6_flowinfo = 0;
358 for (j = 0; j < 5; j++) src->sin6_addr.u.Word[j] = 0;
359 src->sin6_addr.u.Word[5] = 0xffff;
360 src->sin6_addr.u.Word[6] = table->table[i].dwAddr & 0xffff;
361 src->sin6_addr.u.Word[7] = table->table[i].dwAddr >> 16;
362 return TRUE;
366 return FALSE;
369 /******************************************************************
370 * CreateSortedAddressPairs (IPHLPAPI.@)
372 DWORD WINAPI CreateSortedAddressPairs( const PSOCKADDR_IN6 src_list, DWORD src_count,
373 const PSOCKADDR_IN6 dst_list, DWORD dst_count,
374 DWORD options, PSOCKADDR_IN6_PAIR *pair_list,
375 DWORD *pair_count )
377 DWORD i, size, ret;
378 SOCKADDR_IN6_PAIR *pairs;
379 SOCKADDR_IN6 *ptr;
380 SOCKADDR_IN addr4;
381 MIB_IPADDRTABLE *table;
383 FIXME( "(src_list %p src_count %u dst_list %p dst_count %u options %x pair_list %p pair_count %p): stub\n",
384 src_list, src_count, dst_list, dst_count, options, pair_list, pair_count );
386 if (src_list || src_count || !dst_list || !pair_list || !pair_count || dst_count > 500)
387 return ERROR_INVALID_PARAMETER;
389 for (i = 0; i < dst_count; i++)
391 if (!map_address_6to4( &dst_list[i], &addr4 ))
393 FIXME("only mapped IPv4 addresses are supported\n");
394 return ERROR_NOT_SUPPORTED;
398 size = dst_count * sizeof(*pairs);
399 size += dst_count * sizeof(SOCKADDR_IN6) * 2; /* source address + destination address */
400 if (!(pairs = HeapAlloc( GetProcessHeap(), 0, size ))) return ERROR_NOT_ENOUGH_MEMORY;
401 ptr = (SOCKADDR_IN6 *)&pairs[dst_count];
403 if ((ret = getIPAddrTable( &table, GetProcessHeap(), 0 )))
405 HeapFree( GetProcessHeap(), 0, pairs );
406 return ret;
409 for (i = 0; i < dst_count; i++)
411 pairs[i].SourceAddress = ptr++;
412 if (!map_address_6to4( &dst_list[i], &addr4 ) ||
413 !find_src_address( table, &addr4, pairs[i].SourceAddress ))
415 char buf[46];
416 FIXME( "source address for %s not found\n", debugstr_ipv6(&dst_list[i], buf) );
417 memset( pairs[i].SourceAddress, 0, sizeof(*pairs[i].SourceAddress) );
418 pairs[i].SourceAddress->sin6_family = WS_AF_INET6;
421 pairs[i].DestinationAddress = ptr++;
422 memcpy( pairs[i].DestinationAddress, &dst_list[i], sizeof(*pairs[i].DestinationAddress) );
424 *pair_list = pairs;
425 *pair_count = dst_count;
427 HeapFree( GetProcessHeap(), 0, table );
428 return NO_ERROR;
432 /******************************************************************
433 * DeleteIPAddress (IPHLPAPI.@)
435 * Delete an IP address added with AddIPAddress().
437 * PARAMS
438 * NTEContext [In] NTE context from AddIPAddress();
440 * RETURNS
441 * Success: NO_ERROR
442 * Failure: error code from winerror.h
444 * FIXME
445 * Stub, returns ERROR_NOT_SUPPORTED.
447 DWORD WINAPI DeleteIPAddress(ULONG NTEContext)
449 FIXME("(NTEContext %d): stub\n", NTEContext);
450 return ERROR_NOT_SUPPORTED;
454 /******************************************************************
455 * DeleteIpForwardEntry (IPHLPAPI.@)
457 * Delete a route.
459 * PARAMS
460 * pRoute [In] route to delete
462 * RETURNS
463 * Success: NO_ERROR
464 * Failure: error code from winerror.h
466 * FIXME
467 * Stub, returns NO_ERROR.
469 DWORD WINAPI DeleteIpForwardEntry(PMIB_IPFORWARDROW pRoute)
471 FIXME("(pRoute %p): stub\n", pRoute);
472 /* could use SIOCDELRT, not sure I want to */
473 return 0;
477 /******************************************************************
478 * DeleteIpNetEntry (IPHLPAPI.@)
480 * Delete an ARP entry.
482 * PARAMS
483 * pArpEntry [In] ARP entry to delete
485 * RETURNS
486 * Success: NO_ERROR
487 * Failure: error code from winerror.h
489 * FIXME
490 * Stub, returns NO_ERROR.
492 DWORD WINAPI DeleteIpNetEntry(PMIB_IPNETROW pArpEntry)
494 FIXME("(pArpEntry %p): stub\n", pArpEntry);
495 /* could use SIOCDARP on systems that support it, not sure I want to */
496 return 0;
500 /******************************************************************
501 * DeleteProxyArpEntry (IPHLPAPI.@)
503 * Delete a Proxy ARP entry.
505 * PARAMS
506 * dwAddress [In] IP address for which this computer acts as a proxy.
507 * dwMask [In] subnet mask for dwAddress
508 * dwIfIndex [In] interface index
510 * RETURNS
511 * Success: NO_ERROR
512 * Failure: error code from winerror.h
514 * FIXME
515 * Stub, returns ERROR_NOT_SUPPORTED.
517 DWORD WINAPI DeleteProxyArpEntry(DWORD dwAddress, DWORD dwMask, DWORD dwIfIndex)
519 FIXME("(dwAddress 0x%08x, dwMask 0x%08x, dwIfIndex 0x%08x): stub\n",
520 dwAddress, dwMask, dwIfIndex);
521 return ERROR_NOT_SUPPORTED;
525 /******************************************************************
526 * EnableRouter (IPHLPAPI.@)
528 * Turn on ip forwarding.
530 * PARAMS
531 * pHandle [In/Out]
532 * pOverlapped [In/Out] hEvent member should contain a valid handle.
534 * RETURNS
535 * Success: ERROR_IO_PENDING
536 * Failure: error code from winerror.h
538 * FIXME
539 * Stub, returns ERROR_NOT_SUPPORTED.
541 DWORD WINAPI EnableRouter(HANDLE * pHandle, OVERLAPPED * pOverlapped)
543 FIXME("(pHandle %p, pOverlapped %p): stub\n", pHandle, pOverlapped);
544 /* could echo "1" > /proc/net/sys/net/ipv4/ip_forward, not sure I want to
545 could map EACCESS to ERROR_ACCESS_DENIED, I suppose
547 return ERROR_NOT_SUPPORTED;
551 /******************************************************************
552 * FlushIpNetTable (IPHLPAPI.@)
554 * Delete all ARP entries of an interface
556 * PARAMS
557 * dwIfIndex [In] interface index
559 * RETURNS
560 * Success: NO_ERROR
561 * Failure: error code from winerror.h
563 * FIXME
564 * Stub, returns ERROR_NOT_SUPPORTED.
566 DWORD WINAPI FlushIpNetTable(DWORD dwIfIndex)
568 FIXME("(dwIfIndex 0x%08x): stub\n", dwIfIndex);
569 /* this flushes the arp cache of the given index */
570 return ERROR_NOT_SUPPORTED;
573 /******************************************************************
574 * FreeMibTable (IPHLPAPI.@)
576 * Free buffer allocated by network functions
578 * PARAMS
579 * ptr [In] pointer to the buffer to free
582 void WINAPI FreeMibTable(void *ptr)
584 TRACE("(%p)\n", ptr);
585 HeapFree(GetProcessHeap(), 0, ptr);
588 /******************************************************************
589 * GetAdapterIndex (IPHLPAPI.@)
591 * Get interface index from its name.
593 * PARAMS
594 * AdapterName [In] unicode string with the adapter name
595 * IfIndex [Out] returns found interface index
597 * RETURNS
598 * Success: NO_ERROR
599 * Failure: error code from winerror.h
601 DWORD WINAPI GetAdapterIndex(LPWSTR AdapterName, PULONG IfIndex)
603 char adapterName[MAX_ADAPTER_NAME];
604 unsigned int i;
605 DWORD ret;
607 TRACE("(AdapterName %p, IfIndex %p)\n", AdapterName, IfIndex);
608 /* The adapter name is guaranteed not to have any unicode characters, so
609 * this translation is never lossy */
610 for (i = 0; i < sizeof(adapterName) - 1 && AdapterName[i]; i++)
611 adapterName[i] = (char)AdapterName[i];
612 adapterName[i] = '\0';
613 ret = getInterfaceIndexByName(adapterName, IfIndex);
614 TRACE("returning %d\n", ret);
615 return ret;
619 /******************************************************************
620 * GetAdaptersInfo (IPHLPAPI.@)
622 * Get information about adapters.
624 * PARAMS
625 * pAdapterInfo [Out] buffer for adapter infos
626 * pOutBufLen [In] length of output buffer
628 * RETURNS
629 * Success: NO_ERROR
630 * Failure: error code from winerror.h
632 DWORD WINAPI GetAdaptersInfo(PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
634 DWORD ret;
636 TRACE("pAdapterInfo %p, pOutBufLen %p\n", pAdapterInfo, pOutBufLen);
637 if (!pOutBufLen)
638 ret = ERROR_INVALID_PARAMETER;
639 else {
640 DWORD numNonLoopbackInterfaces = get_interface_indices( TRUE, NULL );
642 if (numNonLoopbackInterfaces > 0) {
643 DWORD numIPAddresses = getNumIPAddresses();
644 ULONG size;
646 /* This may slightly overestimate the amount of space needed, because
647 * the IP addresses include the loopback address, but it's easier
648 * to make sure there's more than enough space than to make sure there's
649 * precisely enough space.
651 size = sizeof(IP_ADAPTER_INFO) * numNonLoopbackInterfaces;
652 size += numIPAddresses * sizeof(IP_ADDR_STRING);
653 if (!pAdapterInfo || *pOutBufLen < size) {
654 *pOutBufLen = size;
655 ret = ERROR_BUFFER_OVERFLOW;
657 else {
658 InterfaceIndexTable *table = NULL;
659 PMIB_IPADDRTABLE ipAddrTable = NULL;
660 PMIB_IPFORWARDTABLE routeTable = NULL;
662 ret = getIPAddrTable(&ipAddrTable, GetProcessHeap(), 0);
663 if (!ret)
664 ret = AllocateAndGetIpForwardTableFromStack(&routeTable, FALSE, GetProcessHeap(), 0);
665 if (!ret)
666 get_interface_indices( TRUE, &table );
667 if (table) {
668 size = sizeof(IP_ADAPTER_INFO) * table->numIndexes;
669 size += ipAddrTable->dwNumEntries * sizeof(IP_ADDR_STRING);
670 if (*pOutBufLen < size) {
671 *pOutBufLen = size;
672 ret = ERROR_INSUFFICIENT_BUFFER;
674 else {
675 DWORD ndx;
676 HKEY hKey;
677 BOOL winsEnabled = FALSE;
678 IP_ADDRESS_STRING primaryWINS, secondaryWINS;
679 PIP_ADDR_STRING nextIPAddr = (PIP_ADDR_STRING)((LPBYTE)pAdapterInfo
680 + numNonLoopbackInterfaces * sizeof(IP_ADAPTER_INFO));
682 memset(pAdapterInfo, 0, size);
683 /* @@ Wine registry key: HKCU\Software\Wine\Network */
684 if (RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\Network",
685 &hKey) == ERROR_SUCCESS) {
686 DWORD size = sizeof(primaryWINS.String);
687 unsigned long addr;
689 RegQueryValueExA(hKey, "WinsServer", NULL, NULL,
690 (LPBYTE)primaryWINS.String, &size);
691 addr = inet_addr(primaryWINS.String);
692 if (addr != INADDR_NONE && addr != INADDR_ANY)
693 winsEnabled = TRUE;
694 size = sizeof(secondaryWINS.String);
695 RegQueryValueExA(hKey, "BackupWinsServer", NULL, NULL,
696 (LPBYTE)secondaryWINS.String, &size);
697 addr = inet_addr(secondaryWINS.String);
698 if (addr != INADDR_NONE && addr != INADDR_ANY)
699 winsEnabled = TRUE;
700 RegCloseKey(hKey);
702 for (ndx = 0; ndx < table->numIndexes; ndx++) {
703 PIP_ADAPTER_INFO ptr = &pAdapterInfo[ndx];
704 DWORD i;
705 PIP_ADDR_STRING currentIPAddr = &ptr->IpAddressList;
706 BOOL firstIPAddr = TRUE;
708 /* on Win98 this is left empty, but whatever */
709 getInterfaceNameByIndex(table->indexes[ndx], ptr->AdapterName);
710 getInterfaceNameByIndex(table->indexes[ndx], ptr->Description);
711 ptr->AddressLength = sizeof(ptr->Address);
712 getInterfacePhysicalByIndex(table->indexes[ndx],
713 &ptr->AddressLength, ptr->Address, &ptr->Type);
714 ptr->Index = table->indexes[ndx];
715 for (i = 0; i < ipAddrTable->dwNumEntries; i++) {
716 if (ipAddrTable->table[i].dwIndex == ptr->Index) {
717 if (firstIPAddr) {
718 toIPAddressString(ipAddrTable->table[i].dwAddr,
719 ptr->IpAddressList.IpAddress.String);
720 toIPAddressString(ipAddrTable->table[i].dwMask,
721 ptr->IpAddressList.IpMask.String);
722 firstIPAddr = FALSE;
724 else {
725 currentIPAddr->Next = nextIPAddr;
726 currentIPAddr = nextIPAddr;
727 toIPAddressString(ipAddrTable->table[i].dwAddr,
728 currentIPAddr->IpAddress.String);
729 toIPAddressString(ipAddrTable->table[i].dwMask,
730 currentIPAddr->IpMask.String);
731 nextIPAddr++;
735 /* If no IP was found it probably means that the interface is not
736 * configured. In this case we have to return a zeroed IP and mask. */
737 if (firstIPAddr) {
738 strcpy(ptr->IpAddressList.IpAddress.String, "0.0.0.0");
739 strcpy(ptr->IpAddressList.IpMask.String, "0.0.0.0");
741 /* Find first router through this interface, which we'll assume
742 * is the default gateway for this adapter */
743 for (i = 0; i < routeTable->dwNumEntries; i++)
744 if (routeTable->table[i].dwForwardIfIndex == ptr->Index
745 && routeTable->table[i].u1.ForwardType ==
746 MIB_IPROUTE_TYPE_INDIRECT)
748 toIPAddressString(routeTable->table[i].dwForwardNextHop,
749 ptr->GatewayList.IpAddress.String);
750 toIPAddressString(routeTable->table[i].dwForwardMask,
751 ptr->GatewayList.IpMask.String);
753 if (winsEnabled) {
754 ptr->HaveWins = TRUE;
755 memcpy(ptr->PrimaryWinsServer.IpAddress.String,
756 primaryWINS.String, sizeof(primaryWINS.String));
757 memcpy(ptr->SecondaryWinsServer.IpAddress.String,
758 secondaryWINS.String, sizeof(secondaryWINS.String));
760 if (ndx < table->numIndexes - 1)
761 ptr->Next = &pAdapterInfo[ndx + 1];
762 else
763 ptr->Next = NULL;
765 ptr->DhcpEnabled = TRUE;
767 ret = NO_ERROR;
769 HeapFree(GetProcessHeap(), 0, table);
771 else
772 ret = ERROR_OUTOFMEMORY;
773 HeapFree(GetProcessHeap(), 0, routeTable);
774 HeapFree(GetProcessHeap(), 0, ipAddrTable);
777 else
778 ret = ERROR_NO_DATA;
780 TRACE("returning %d\n", ret);
781 return ret;
784 static DWORD typeFromMibType(DWORD mib_type)
786 switch (mib_type)
788 case MIB_IF_TYPE_ETHERNET: return IF_TYPE_ETHERNET_CSMACD;
789 case MIB_IF_TYPE_TOKENRING: return IF_TYPE_ISO88025_TOKENRING;
790 case MIB_IF_TYPE_PPP: return IF_TYPE_PPP;
791 case MIB_IF_TYPE_LOOPBACK: return IF_TYPE_SOFTWARE_LOOPBACK;
792 default: return IF_TYPE_OTHER;
796 static NET_IF_CONNECTION_TYPE connectionTypeFromMibType(DWORD mib_type)
798 switch (mib_type)
800 case MIB_IF_TYPE_PPP: return NET_IF_CONNECTION_DEMAND;
801 case MIB_IF_TYPE_SLIP: return NET_IF_CONNECTION_DEMAND;
802 default: return NET_IF_CONNECTION_DEDICATED;
806 static ULONG v4addressesFromIndex(IF_INDEX index, DWORD **addrs, ULONG *num_addrs, DWORD **masks)
808 ULONG ret, i, j;
809 MIB_IPADDRTABLE *at;
811 *num_addrs = 0;
812 if ((ret = getIPAddrTable(&at, GetProcessHeap(), 0))) return ret;
813 for (i = 0; i < at->dwNumEntries; i++)
815 if (at->table[i].dwIndex == index) (*num_addrs)++;
817 if (!(*addrs = HeapAlloc(GetProcessHeap(), 0, *num_addrs * sizeof(DWORD))))
819 HeapFree(GetProcessHeap(), 0, at);
820 return ERROR_OUTOFMEMORY;
822 if (!(*masks = HeapAlloc(GetProcessHeap(), 0, *num_addrs * sizeof(DWORD))))
824 HeapFree(GetProcessHeap(), 0, *addrs);
825 HeapFree(GetProcessHeap(), 0, at);
826 return ERROR_OUTOFMEMORY;
828 for (i = 0, j = 0; i < at->dwNumEntries; i++)
830 if (at->table[i].dwIndex == index)
832 (*addrs)[j] = at->table[i].dwAddr;
833 (*masks)[j] = at->table[i].dwMask;
834 j++;
837 HeapFree(GetProcessHeap(), 0, at);
838 return ERROR_SUCCESS;
841 static char *debugstr_ipv4(const in_addr_t *in_addr, char *buf)
843 const BYTE *addrp;
844 char *p = buf;
846 for (addrp = (const BYTE *)in_addr;
847 addrp - (const BYTE *)in_addr < sizeof(*in_addr);
848 addrp++)
850 if (addrp == (const BYTE *)in_addr + sizeof(*in_addr) - 1)
851 sprintf(p, "%d", *addrp);
852 else
853 p += sprintf(p, "%d.", *addrp);
855 return buf;
858 static ULONG count_v4_gateways(DWORD index, PMIB_IPFORWARDTABLE routeTable)
860 DWORD i, num_gateways = 0;
862 for (i = 0; i < routeTable->dwNumEntries; i++)
864 if (routeTable->table[i].dwForwardIfIndex == index &&
865 routeTable->table[i].u1.ForwardType == MIB_IPROUTE_TYPE_INDIRECT)
866 num_gateways++;
868 return num_gateways;
871 static DWORD mask_v4_to_prefix(DWORD m)
873 #ifdef HAVE___BUILTIN_POPCOUNT
874 return __builtin_popcount(m);
875 #else
876 m -= m >> 1 & 0x55555555;
877 m = (m & 0x33333333) + (m >> 2 & 0x33333333);
878 return ((m + (m >> 4)) & 0x0f0f0f0f) * 0x01010101 >> 24;
879 #endif
882 static DWORD mask_v6_to_prefix(SOCKET_ADDRESS *m)
884 const IN6_ADDR *mask = &((struct WS_sockaddr_in6 *)m->lpSockaddr)->sin6_addr;
885 DWORD ret = 0, i;
887 for (i = 0; i < 8; i++)
888 ret += mask_v4_to_prefix(mask->u.Word[i]);
889 return ret;
892 static PMIB_IPFORWARDROW findIPv4Gateway(DWORD index,
893 PMIB_IPFORWARDTABLE routeTable)
895 DWORD i;
896 PMIB_IPFORWARDROW row = NULL;
898 for (i = 0; !row && i < routeTable->dwNumEntries; i++)
900 if (routeTable->table[i].dwForwardIfIndex == index &&
901 routeTable->table[i].u1.ForwardType == MIB_IPROUTE_TYPE_INDIRECT)
902 row = &routeTable->table[i];
904 return row;
907 static void fill_unicast_addr_data(IP_ADAPTER_ADDRESSES *aa, IP_ADAPTER_UNICAST_ADDRESS *ua)
909 /* Actually this information should be read somewhere from the system
910 * but it doesn't matter much for the bugs found so far.
911 * This information is required for DirectPlay8 games. */
912 if (aa->IfType != IF_TYPE_SOFTWARE_LOOPBACK)
914 ua->PrefixOrigin = IpPrefixOriginDhcp;
915 ua->SuffixOrigin = IpSuffixOriginDhcp;
917 else
919 ua->PrefixOrigin = IpPrefixOriginManual;
920 ua->SuffixOrigin = IpSuffixOriginManual;
923 /* The address is not duplicated in the network */
924 ua->DadState = IpDadStatePreferred;
926 /* Some address life time values, required even for non-dhcp addresses */
927 ua->ValidLifetime = 60000;
928 ua->PreferredLifetime = 60000;
929 ua->LeaseLifetime = 60000;
932 static ULONG adapterAddressesFromIndex(ULONG family, ULONG flags, IF_INDEX index,
933 IP_ADAPTER_ADDRESSES *aa, ULONG *size)
935 ULONG ret = ERROR_SUCCESS, i, j, num_v4addrs = 0, num_v4_gateways = 0, num_v6addrs = 0, total_size;
936 DWORD *v4addrs = NULL, *v4masks = NULL;
937 SOCKET_ADDRESS *v6addrs = NULL, *v6masks = NULL;
938 PMIB_IPFORWARDTABLE routeTable = NULL;
940 if (family == WS_AF_INET)
942 ret = v4addressesFromIndex(index, &v4addrs, &num_v4addrs, &v4masks);
944 if (!ret && flags & GAA_FLAG_INCLUDE_ALL_GATEWAYS)
946 ret = AllocateAndGetIpForwardTableFromStack(&routeTable, FALSE, GetProcessHeap(), 0);
947 if (!ret) num_v4_gateways = count_v4_gateways(index, routeTable);
950 else if (family == WS_AF_INET6)
952 ret = v6addressesFromIndex(index, &v6addrs, &num_v6addrs, &v6masks);
954 else if (family == WS_AF_UNSPEC)
956 ret = v4addressesFromIndex(index, &v4addrs, &num_v4addrs, &v4masks);
958 if (!ret && flags & GAA_FLAG_INCLUDE_ALL_GATEWAYS)
960 ret = AllocateAndGetIpForwardTableFromStack(&routeTable, FALSE, GetProcessHeap(), 0);
961 if (!ret) num_v4_gateways = count_v4_gateways(index, routeTable);
963 if (!ret) ret = v6addressesFromIndex(index, &v6addrs, &num_v6addrs, &v6masks);
965 else
967 FIXME("address family %u unsupported\n", family);
968 ret = ERROR_NO_DATA;
970 if (ret)
972 HeapFree(GetProcessHeap(), 0, v4addrs);
973 HeapFree(GetProcessHeap(), 0, v4masks);
974 HeapFree(GetProcessHeap(), 0, v6addrs);
975 HeapFree(GetProcessHeap(), 0, v6masks);
976 HeapFree(GetProcessHeap(), 0, routeTable);
977 return ret;
980 total_size = sizeof(IP_ADAPTER_ADDRESSES);
981 total_size += 39; /* "{00000000-0000-0000-0000-000000000000}" */
982 total_size += IF_NAMESIZE * sizeof(WCHAR);
983 if (!(flags & GAA_FLAG_SKIP_FRIENDLY_NAME))
984 total_size += IF_NAMESIZE * sizeof(WCHAR);
985 if (flags & GAA_FLAG_INCLUDE_PREFIX)
987 total_size += sizeof(IP_ADAPTER_PREFIX) * num_v4addrs;
988 total_size += sizeof(IP_ADAPTER_PREFIX) * num_v6addrs;
989 total_size += sizeof(struct sockaddr_in) * num_v4addrs;
990 for (i = 0; i < num_v6addrs; i++)
991 total_size += v6masks[i].iSockaddrLength;
993 total_size += sizeof(IP_ADAPTER_UNICAST_ADDRESS) * num_v4addrs;
994 total_size += sizeof(struct sockaddr_in) * num_v4addrs;
995 total_size += (sizeof(IP_ADAPTER_GATEWAY_ADDRESS) + sizeof(SOCKADDR_IN)) * num_v4_gateways;
996 total_size += sizeof(IP_ADAPTER_UNICAST_ADDRESS) * num_v6addrs;
997 total_size += sizeof(SOCKET_ADDRESS) * num_v6addrs;
998 for (i = 0; i < num_v6addrs; i++)
999 total_size += v6addrs[i].iSockaddrLength;
1001 if (aa && *size >= total_size)
1003 char name[IF_NAMESIZE], *ptr = (char *)aa + sizeof(IP_ADAPTER_ADDRESSES), *src;
1004 WCHAR *dst;
1005 DWORD buflen, type;
1006 INTERNAL_IF_OPER_STATUS status;
1008 memset(aa, 0, sizeof(IP_ADAPTER_ADDRESSES));
1009 aa->u.s.Length = sizeof(IP_ADAPTER_ADDRESSES);
1010 aa->u.s.IfIndex = index;
1012 sprintf(ptr, "{%08x-0000-0000-0000-000000000000}", index);
1013 aa->AdapterName = ptr;
1014 ptr += 39;
1016 getInterfaceNameByIndex(index, name);
1017 if (!(flags & GAA_FLAG_SKIP_FRIENDLY_NAME))
1019 aa->FriendlyName = (WCHAR *)ptr;
1020 for (src = name, dst = (WCHAR *)ptr; *src; src++, dst++)
1021 *dst = *src;
1022 *dst++ = 0;
1023 ptr = (char *)dst;
1025 aa->Description = (WCHAR *)ptr;
1026 for (src = name, dst = (WCHAR *)ptr; *src; src++, dst++)
1027 *dst = *src;
1028 *dst++ = 0;
1029 ptr = (char *)dst;
1031 TRACE("%s: %d IPv4 addresses, %d IPv6 addresses:\n", name, num_v4addrs,
1032 num_v6addrs);
1034 buflen = MAX_INTERFACE_PHYSADDR;
1035 getInterfacePhysicalByIndex(index, &buflen, aa->PhysicalAddress, &type);
1036 aa->PhysicalAddressLength = buflen;
1037 aa->IfType = typeFromMibType(type);
1038 aa->ConnectionType = connectionTypeFromMibType(type);
1039 aa->Luid.Info.NetLuidIndex = index;
1040 aa->Luid.Info.IfType = aa->IfType;
1042 if (num_v4_gateways)
1044 PMIB_IPFORWARDROW adapterRow;
1046 if ((adapterRow = findIPv4Gateway(index, routeTable)))
1048 PIP_ADAPTER_GATEWAY_ADDRESS gw;
1049 PSOCKADDR_IN sin;
1051 gw = (PIP_ADAPTER_GATEWAY_ADDRESS)ptr;
1052 aa->FirstGatewayAddress = gw;
1054 gw->u.s.Length = sizeof(IP_ADAPTER_GATEWAY_ADDRESS);
1055 ptr += sizeof(IP_ADAPTER_GATEWAY_ADDRESS);
1056 sin = (PSOCKADDR_IN)ptr;
1057 sin->sin_family = WS_AF_INET;
1058 sin->sin_port = 0;
1059 memcpy(&sin->sin_addr, &adapterRow->dwForwardNextHop,
1060 sizeof(DWORD));
1061 gw->Address.lpSockaddr = (LPSOCKADDR)sin;
1062 gw->Address.iSockaddrLength = sizeof(SOCKADDR_IN);
1063 gw->Next = NULL;
1064 ptr += sizeof(SOCKADDR_IN);
1067 if (num_v4addrs && !(flags & GAA_FLAG_SKIP_UNICAST))
1069 IP_ADAPTER_UNICAST_ADDRESS *ua;
1070 struct WS_sockaddr_in *sa;
1071 aa->u1.s1.Ipv4Enabled = TRUE;
1072 ua = aa->FirstUnicastAddress = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1073 for (i = 0; i < num_v4addrs; i++)
1075 char addr_buf[16];
1077 memset(ua, 0, sizeof(IP_ADAPTER_UNICAST_ADDRESS));
1078 ua->u.s.Length = sizeof(IP_ADAPTER_UNICAST_ADDRESS);
1079 ua->Address.iSockaddrLength = sizeof(struct sockaddr_in);
1080 ua->Address.lpSockaddr = (SOCKADDR *)((char *)ua + ua->u.s.Length);
1082 sa = (struct WS_sockaddr_in *)ua->Address.lpSockaddr;
1083 sa->sin_family = WS_AF_INET;
1084 sa->sin_addr.S_un.S_addr = v4addrs[i];
1085 sa->sin_port = 0;
1086 TRACE("IPv4 %d/%d: %s\n", i + 1, num_v4addrs,
1087 debugstr_ipv4(&sa->sin_addr.S_un.S_addr, addr_buf));
1088 fill_unicast_addr_data(aa, ua);
1090 ua->OnLinkPrefixLength = mask_v4_to_prefix(v4masks[i]);
1092 ptr += ua->u.s.Length + ua->Address.iSockaddrLength;
1093 if (i < num_v4addrs - 1)
1095 ua->Next = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1096 ua = ua->Next;
1100 if (num_v6addrs && !(flags & GAA_FLAG_SKIP_UNICAST))
1102 IP_ADAPTER_UNICAST_ADDRESS *ua;
1103 struct WS_sockaddr_in6 *sa;
1105 aa->u1.s1.Ipv6Enabled = TRUE;
1106 if (aa->FirstUnicastAddress)
1108 for (ua = aa->FirstUnicastAddress; ua->Next; ua = ua->Next)
1110 ua->Next = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1111 ua = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1113 else
1114 ua = aa->FirstUnicastAddress = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1115 for (i = 0; i < num_v6addrs; i++)
1117 char addr_buf[46];
1119 memset(ua, 0, sizeof(IP_ADAPTER_UNICAST_ADDRESS));
1120 ua->u.s.Length = sizeof(IP_ADAPTER_UNICAST_ADDRESS);
1121 ua->Address.iSockaddrLength = v6addrs[i].iSockaddrLength;
1122 ua->Address.lpSockaddr = (SOCKADDR *)((char *)ua + ua->u.s.Length);
1124 sa = (struct WS_sockaddr_in6 *)ua->Address.lpSockaddr;
1125 memcpy(sa, v6addrs[i].lpSockaddr, sizeof(*sa));
1126 TRACE("IPv6 %d/%d: %s\n", i + 1, num_v6addrs,
1127 debugstr_ipv6(sa, addr_buf));
1128 fill_unicast_addr_data(aa, ua);
1130 ua->OnLinkPrefixLength = mask_v6_to_prefix(&v6masks[i]);
1132 ptr += ua->u.s.Length + ua->Address.iSockaddrLength;
1133 if (i < num_v6addrs - 1)
1135 ua->Next = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
1136 ua = ua->Next;
1140 if (num_v4addrs && (flags & GAA_FLAG_INCLUDE_PREFIX))
1142 IP_ADAPTER_PREFIX *prefix;
1144 prefix = aa->FirstPrefix = (IP_ADAPTER_PREFIX *)ptr;
1145 for (i = 0; i < num_v4addrs; i++)
1147 char addr_buf[16];
1148 struct WS_sockaddr_in *sa;
1150 prefix->u.s.Length = sizeof(*prefix);
1151 prefix->u.s.Flags = 0;
1152 prefix->Next = NULL;
1153 prefix->Address.iSockaddrLength = sizeof(struct sockaddr_in);
1154 prefix->Address.lpSockaddr = (SOCKADDR *)((char *)prefix + prefix->u.s.Length);
1156 sa = (struct WS_sockaddr_in *)prefix->Address.lpSockaddr;
1157 sa->sin_family = WS_AF_INET;
1158 sa->sin_addr.S_un.S_addr = v4addrs[i] & v4masks[i];
1159 sa->sin_port = 0;
1161 prefix->PrefixLength = mask_v4_to_prefix(v4masks[i]);
1163 TRACE("IPv4 network: %s/%u\n",
1164 debugstr_ipv4((const in_addr_t *)&sa->sin_addr.S_un.S_addr, addr_buf),
1165 prefix->PrefixLength);
1167 ptr += prefix->u.s.Length + prefix->Address.iSockaddrLength;
1168 if (i < num_v4addrs - 1)
1170 prefix->Next = (IP_ADAPTER_PREFIX *)ptr;
1171 prefix = prefix->Next;
1175 if (num_v6addrs && (flags & GAA_FLAG_INCLUDE_PREFIX))
1177 IP_ADAPTER_PREFIX *prefix;
1179 if (aa->FirstPrefix)
1181 for (prefix = aa->FirstPrefix; prefix->Next; prefix = prefix->Next)
1183 prefix->Next = (IP_ADAPTER_PREFIX *)ptr;
1184 prefix = (IP_ADAPTER_PREFIX *)ptr;
1186 else
1187 prefix = aa->FirstPrefix = (IP_ADAPTER_PREFIX *)ptr;
1188 for (i = 0; i < num_v6addrs; i++)
1190 char addr_buf[46];
1191 struct WS_sockaddr_in6 *sa;
1192 const IN6_ADDR *addr, *mask;
1194 prefix->u.s.Length = sizeof(*prefix);
1195 prefix->u.s.Flags = 0;
1196 prefix->Next = NULL;
1197 prefix->Address.iSockaddrLength = sizeof(struct sockaddr_in6);
1198 prefix->Address.lpSockaddr = (SOCKADDR *)((char *)prefix + prefix->u.s.Length);
1200 sa = (struct WS_sockaddr_in6 *)prefix->Address.lpSockaddr;
1201 sa->sin6_family = WS_AF_INET6;
1202 sa->sin6_port = 0;
1203 sa->sin6_flowinfo = 0;
1204 addr = &((struct WS_sockaddr_in6 *)v6addrs[i].lpSockaddr)->sin6_addr;
1205 mask = &((struct WS_sockaddr_in6 *)v6masks[i].lpSockaddr)->sin6_addr;
1206 for (j = 0; j < 8; j++) sa->sin6_addr.u.Word[j] = addr->u.Word[j] & mask->u.Word[j];
1207 sa->sin6_scope_id = 0;
1209 prefix->PrefixLength = mask_v6_to_prefix(&v6masks[i]);
1211 TRACE("IPv6 network: %s/%u\n", debugstr_ipv6(sa, addr_buf), prefix->PrefixLength);
1213 ptr += prefix->u.s.Length + prefix->Address.iSockaddrLength;
1214 if (i < num_v6addrs - 1)
1216 prefix->Next = (IP_ADAPTER_PREFIX *)ptr;
1217 prefix = prefix->Next;
1222 getInterfaceMtuByName(name, &aa->Mtu);
1224 getInterfaceStatusByName(name, &status);
1225 if (status == MIB_IF_OPER_STATUS_OPERATIONAL) aa->OperStatus = IfOperStatusUp;
1226 else if (status == MIB_IF_OPER_STATUS_NON_OPERATIONAL) aa->OperStatus = IfOperStatusDown;
1227 else aa->OperStatus = IfOperStatusUnknown;
1229 *size = total_size;
1230 HeapFree(GetProcessHeap(), 0, routeTable);
1231 HeapFree(GetProcessHeap(), 0, v6addrs);
1232 HeapFree(GetProcessHeap(), 0, v6masks);
1233 HeapFree(GetProcessHeap(), 0, v4addrs);
1234 HeapFree(GetProcessHeap(), 0, v4masks);
1235 return ERROR_SUCCESS;
1238 static void sockaddr_in_to_WS_storage( SOCKADDR_STORAGE *dst, const struct sockaddr_in *src )
1240 SOCKADDR_IN *s = (SOCKADDR_IN *)dst;
1242 s->sin_family = WS_AF_INET;
1243 s->sin_port = src->sin_port;
1244 memcpy( &s->sin_addr, &src->sin_addr, sizeof(IN_ADDR) );
1245 memset( (char *)s + FIELD_OFFSET( SOCKADDR_IN, sin_zero ), 0,
1246 sizeof(SOCKADDR_STORAGE) - FIELD_OFFSET( SOCKADDR_IN, sin_zero) );
1249 static void sockaddr_in6_to_WS_storage( SOCKADDR_STORAGE *dst, const struct sockaddr_in6 *src )
1251 SOCKADDR_IN6 *s = (SOCKADDR_IN6 *)dst;
1253 s->sin6_family = WS_AF_INET6;
1254 s->sin6_port = src->sin6_port;
1255 s->sin6_flowinfo = src->sin6_flowinfo;
1256 memcpy( &s->sin6_addr, &src->sin6_addr, sizeof(IN6_ADDR) );
1257 s->sin6_scope_id = src->sin6_scope_id;
1258 memset( (char *)s + sizeof(SOCKADDR_IN6), 0,
1259 sizeof(SOCKADDR_STORAGE) - sizeof(SOCKADDR_IN6) );
1262 #ifdef HAVE_STRUCT___RES_STATE
1263 /* call res_init() just once because of a bug in Mac OS X 10.4 */
1264 /* Call once per thread on systems that have per-thread _res. */
1266 static CRITICAL_SECTION res_init_cs;
1267 static CRITICAL_SECTION_DEBUG res_init_cs_debug = {
1268 0, 0, &res_init_cs,
1269 { &res_init_cs_debug.ProcessLocksList, &res_init_cs_debug.ProcessLocksList },
1270 0, 0, { (DWORD_PTR)(__FILE__ ": res_init_cs") }
1272 static CRITICAL_SECTION res_init_cs = { &res_init_cs_debug, -1, 0, 0, 0, 0 };
1274 static void initialise_resolver(void)
1276 EnterCriticalSection(&res_init_cs);
1277 if ((_res.options & RES_INIT) == 0)
1278 res_init();
1279 LeaveCriticalSection(&res_init_cs);
1282 static int get_dns_servers( SOCKADDR_STORAGE *servers, int num, BOOL ip4_only )
1284 int i, ip6_count = 0;
1285 SOCKADDR_STORAGE *addr;
1287 initialise_resolver();
1289 #ifdef HAVE_STRUCT___RES_STATE__U__EXT_NSCOUNT6
1290 ip6_count = _res._u._ext.nscount6;
1291 #endif
1293 if (!servers || !num)
1295 num = _res.nscount;
1296 if (ip4_only) num -= ip6_count;
1297 return num;
1300 for (i = 0, addr = servers; addr < (servers + num) && i < _res.nscount; i++)
1302 #ifdef HAVE_STRUCT___RES_STATE__U__EXT_NSCOUNT6
1303 if (_res._u._ext.nsaddrs[i])
1305 if (ip4_only) continue;
1306 sockaddr_in6_to_WS_storage( addr, _res._u._ext.nsaddrs[i] );
1308 else
1309 #endif
1311 sockaddr_in_to_WS_storage( addr, _res.nsaddr_list + i );
1313 addr++;
1315 return addr - servers;
1317 #elif defined(HAVE___RES_GET_STATE) && defined(HAVE___RES_GETSERVERS)
1319 static int get_dns_servers( SOCKADDR_STORAGE *servers, int num, BOOL ip4_only )
1321 extern struct res_state *__res_get_state( void );
1322 extern int __res_getservers( struct res_state *, struct sockaddr_storage *, int );
1323 struct res_state *state = __res_get_state();
1324 int i, found = 0, total = __res_getservers( state, NULL, 0 );
1325 SOCKADDR_STORAGE *addr = servers;
1326 struct sockaddr_storage *buf;
1328 if ((!servers || !num) && !ip4_only) return total;
1330 buf = HeapAlloc( GetProcessHeap(), 0, total * sizeof(struct sockaddr_storage) );
1331 total = __res_getservers( state, buf, total );
1333 for (i = 0; i < total; i++)
1335 if (buf[i].ss_family == AF_INET6 && ip4_only) continue;
1336 if (buf[i].ss_family != AF_INET && buf[i].ss_family != AF_INET6) continue;
1338 found++;
1339 if (!servers || !num) continue;
1341 if (buf[i].ss_family == AF_INET6)
1343 sockaddr_in6_to_WS_storage( addr, (struct sockaddr_in6 *)(buf + i) );
1345 else
1347 sockaddr_in_to_WS_storage( addr, (struct sockaddr_in *)(buf + i) );
1349 if (++addr >= servers + num) break;
1352 HeapFree( GetProcessHeap(), 0, buf );
1353 return found;
1355 #else
1357 static int get_dns_servers( SOCKADDR_STORAGE *servers, int num, BOOL ip4_only )
1359 FIXME("Unimplemented on this system\n");
1360 return 0;
1362 #endif
1364 static ULONG get_dns_server_addresses(PIP_ADAPTER_DNS_SERVER_ADDRESS address, ULONG *len)
1366 int num = get_dns_servers( NULL, 0, FALSE );
1367 DWORD size;
1369 size = num * (sizeof(IP_ADAPTER_DNS_SERVER_ADDRESS) + sizeof(SOCKADDR_STORAGE));
1370 if (!address || *len < size)
1372 *len = size;
1373 return ERROR_BUFFER_OVERFLOW;
1375 *len = size;
1376 if (num > 0)
1378 PIP_ADAPTER_DNS_SERVER_ADDRESS addr = address;
1379 SOCKADDR_STORAGE *sock_addrs = (SOCKADDR_STORAGE *)(address + num);
1380 int i;
1382 get_dns_servers( sock_addrs, num, FALSE );
1384 for (i = 0; i < num; i++, addr = addr->Next)
1386 addr->u.s.Length = sizeof(*addr);
1387 if (sock_addrs[i].ss_family == WS_AF_INET6)
1388 addr->Address.iSockaddrLength = sizeof(SOCKADDR_IN6);
1389 else
1390 addr->Address.iSockaddrLength = sizeof(SOCKADDR_IN);
1391 addr->Address.lpSockaddr = (SOCKADDR *)(sock_addrs + i);
1392 if (i == num - 1)
1393 addr->Next = NULL;
1394 else
1395 addr->Next = addr + 1;
1398 return ERROR_SUCCESS;
1401 #ifdef HAVE_STRUCT___RES_STATE
1402 static BOOL is_ip_address_string(const char *str)
1404 struct in_addr in;
1405 int ret;
1407 ret = inet_aton(str, &in);
1408 return ret != 0;
1410 #endif
1412 static ULONG get_dns_suffix(WCHAR *suffix, ULONG *len)
1414 ULONG size;
1415 const char *found_suffix = "";
1416 /* Always return a NULL-terminated string, even if it's empty. */
1418 #ifdef HAVE_STRUCT___RES_STATE
1420 ULONG i;
1421 initialise_resolver();
1422 for (i = 0; !*found_suffix && i < MAXDNSRCH + 1 && _res.dnsrch[i]; i++)
1424 /* This uses a heuristic to select a DNS suffix:
1425 * the first, non-IP address string is selected.
1427 if (!is_ip_address_string(_res.dnsrch[i]))
1428 found_suffix = _res.dnsrch[i];
1431 #endif
1433 size = MultiByteToWideChar( CP_UNIXCP, 0, found_suffix, -1, NULL, 0 ) * sizeof(WCHAR);
1434 if (!suffix || *len < size)
1436 *len = size;
1437 return ERROR_BUFFER_OVERFLOW;
1439 *len = MultiByteToWideChar( CP_UNIXCP, 0, found_suffix, -1, suffix, *len / sizeof(WCHAR) ) * sizeof(WCHAR);
1440 return ERROR_SUCCESS;
1443 ULONG WINAPI DECLSPEC_HOTPATCH GetAdaptersAddresses(ULONG family, ULONG flags, PVOID reserved,
1444 PIP_ADAPTER_ADDRESSES aa, PULONG buflen)
1446 InterfaceIndexTable *table;
1447 ULONG i, size, dns_server_size = 0, dns_suffix_size, total_size, ret = ERROR_NO_DATA;
1449 TRACE("(%d, %08x, %p, %p, %p)\n", family, flags, reserved, aa, buflen);
1451 if (!buflen) return ERROR_INVALID_PARAMETER;
1453 get_interface_indices( FALSE, &table );
1454 if (!table || !table->numIndexes)
1456 HeapFree(GetProcessHeap(), 0, table);
1457 return ERROR_NO_DATA;
1459 total_size = 0;
1460 for (i = 0; i < table->numIndexes; i++)
1462 size = 0;
1463 if ((ret = adapterAddressesFromIndex(family, flags, table->indexes[i], NULL, &size)))
1465 HeapFree(GetProcessHeap(), 0, table);
1466 return ret;
1468 total_size += size;
1470 if (!(flags & GAA_FLAG_SKIP_DNS_SERVER))
1472 /* Since DNS servers aren't really per adapter, get enough space for a
1473 * single copy of them.
1475 get_dns_server_addresses(NULL, &dns_server_size);
1476 total_size += dns_server_size;
1478 /* Since DNS suffix also isn't really per adapter, get enough space for a
1479 * single copy of it.
1481 get_dns_suffix(NULL, &dns_suffix_size);
1482 total_size += dns_suffix_size;
1483 if (aa && *buflen >= total_size)
1485 ULONG bytes_left = size = total_size;
1486 PIP_ADAPTER_ADDRESSES first_aa = aa;
1487 PIP_ADAPTER_DNS_SERVER_ADDRESS firstDns;
1488 WCHAR *dnsSuffix;
1490 for (i = 0; i < table->numIndexes; i++)
1492 if ((ret = adapterAddressesFromIndex(family, flags, table->indexes[i], aa, &size)))
1494 HeapFree(GetProcessHeap(), 0, table);
1495 return ret;
1497 if (i < table->numIndexes - 1)
1499 aa->Next = (IP_ADAPTER_ADDRESSES *)((char *)aa + size);
1500 aa = aa->Next;
1501 size = bytes_left -= size;
1504 if (dns_server_size)
1506 firstDns = (PIP_ADAPTER_DNS_SERVER_ADDRESS)((BYTE *)first_aa + total_size - dns_server_size - dns_suffix_size);
1507 get_dns_server_addresses(firstDns, &dns_server_size);
1508 for (aa = first_aa; aa; aa = aa->Next)
1510 if (aa->IfType != IF_TYPE_SOFTWARE_LOOPBACK && aa->OperStatus == IfOperStatusUp)
1511 aa->FirstDnsServerAddress = firstDns;
1514 aa = first_aa;
1515 dnsSuffix = (WCHAR *)((BYTE *)aa + total_size - dns_suffix_size);
1516 get_dns_suffix(dnsSuffix, &dns_suffix_size);
1517 for (; aa; aa = aa->Next)
1519 if (aa->IfType != IF_TYPE_SOFTWARE_LOOPBACK && aa->OperStatus == IfOperStatusUp)
1520 aa->DnsSuffix = dnsSuffix;
1521 else
1522 aa->DnsSuffix = dnsSuffix + dns_suffix_size / sizeof(WCHAR) - 1;
1524 ret = ERROR_SUCCESS;
1526 else
1528 ret = ERROR_BUFFER_OVERFLOW;
1529 *buflen = total_size;
1532 TRACE("num adapters %u\n", table->numIndexes);
1533 HeapFree(GetProcessHeap(), 0, table);
1534 return ret;
1537 /******************************************************************
1538 * GetBestInterface (IPHLPAPI.@)
1540 * Get the interface, with the best route for the given IP address.
1542 * PARAMS
1543 * dwDestAddr [In] IP address to search the interface for
1544 * pdwBestIfIndex [Out] found best interface
1546 * RETURNS
1547 * Success: NO_ERROR
1548 * Failure: error code from winerror.h
1550 DWORD WINAPI GetBestInterface(IPAddr dwDestAddr, PDWORD pdwBestIfIndex)
1552 struct WS_sockaddr_in sa_in;
1553 memset(&sa_in, 0, sizeof(sa_in));
1554 sa_in.sin_family = WS_AF_INET;
1555 sa_in.sin_addr.S_un.S_addr = dwDestAddr;
1556 return GetBestInterfaceEx((struct WS_sockaddr *)&sa_in, pdwBestIfIndex);
1559 /******************************************************************
1560 * GetBestInterfaceEx (IPHLPAPI.@)
1562 * Get the interface, with the best route for the given IP address.
1564 * PARAMS
1565 * dwDestAddr [In] IP address to search the interface for
1566 * pdwBestIfIndex [Out] found best interface
1568 * RETURNS
1569 * Success: NO_ERROR
1570 * Failure: error code from winerror.h
1572 DWORD WINAPI GetBestInterfaceEx(struct WS_sockaddr *pDestAddr, PDWORD pdwBestIfIndex)
1574 DWORD ret;
1576 TRACE("pDestAddr %p, pdwBestIfIndex %p\n", pDestAddr, pdwBestIfIndex);
1577 if (!pDestAddr || !pdwBestIfIndex)
1578 ret = ERROR_INVALID_PARAMETER;
1579 else {
1580 MIB_IPFORWARDROW ipRow;
1582 if (pDestAddr->sa_family == WS_AF_INET) {
1583 ret = GetBestRoute(((struct WS_sockaddr_in *)pDestAddr)->sin_addr.S_un.S_addr, 0, &ipRow);
1584 if (ret == ERROR_SUCCESS)
1585 *pdwBestIfIndex = ipRow.dwForwardIfIndex;
1586 } else {
1587 FIXME("address family %d not supported\n", pDestAddr->sa_family);
1588 ret = ERROR_NOT_SUPPORTED;
1591 TRACE("returning %d\n", ret);
1592 return ret;
1596 /******************************************************************
1597 * GetBestRoute (IPHLPAPI.@)
1599 * Get the best route for the given IP address.
1601 * PARAMS
1602 * dwDestAddr [In] IP address to search the best route for
1603 * dwSourceAddr [In] optional source IP address
1604 * pBestRoute [Out] found best route
1606 * RETURNS
1607 * Success: NO_ERROR
1608 * Failure: error code from winerror.h
1610 DWORD WINAPI GetBestRoute(DWORD dwDestAddr, DWORD dwSourceAddr, PMIB_IPFORWARDROW pBestRoute)
1612 PMIB_IPFORWARDTABLE table;
1613 DWORD ret;
1615 TRACE("dwDestAddr 0x%08x, dwSourceAddr 0x%08x, pBestRoute %p\n", dwDestAddr,
1616 dwSourceAddr, pBestRoute);
1617 if (!pBestRoute)
1618 return ERROR_INVALID_PARAMETER;
1620 ret = AllocateAndGetIpForwardTableFromStack(&table, FALSE, GetProcessHeap(), 0);
1621 if (!ret) {
1622 DWORD ndx, matchedBits, matchedNdx = table->dwNumEntries;
1624 for (ndx = 0, matchedBits = 0; ndx < table->dwNumEntries; ndx++) {
1625 if (table->table[ndx].u1.ForwardType != MIB_IPROUTE_TYPE_INVALID &&
1626 (dwDestAddr & table->table[ndx].dwForwardMask) ==
1627 (table->table[ndx].dwForwardDest & table->table[ndx].dwForwardMask)) {
1628 DWORD numShifts, mask;
1630 for (numShifts = 0, mask = table->table[ndx].dwForwardMask;
1631 mask && mask & 1; mask >>= 1, numShifts++)
1633 if (numShifts > matchedBits) {
1634 matchedBits = numShifts;
1635 matchedNdx = ndx;
1637 else if (!matchedBits) {
1638 matchedNdx = ndx;
1642 if (matchedNdx < table->dwNumEntries) {
1643 memcpy(pBestRoute, &table->table[matchedNdx], sizeof(MIB_IPFORWARDROW));
1644 ret = ERROR_SUCCESS;
1646 else {
1647 /* No route matches, which can happen if there's no default route. */
1648 ret = ERROR_HOST_UNREACHABLE;
1650 HeapFree(GetProcessHeap(), 0, table);
1652 TRACE("returning %d\n", ret);
1653 return ret;
1657 /******************************************************************
1658 * GetFriendlyIfIndex (IPHLPAPI.@)
1660 * Get a "friendly" version of IfIndex, which is one that doesn't
1661 * have the top byte set. Doesn't validate whether IfIndex is a valid
1662 * adapter index.
1664 * PARAMS
1665 * IfIndex [In] interface index to get the friendly one for
1667 * RETURNS
1668 * A friendly version of IfIndex.
1670 DWORD WINAPI GetFriendlyIfIndex(DWORD IfIndex)
1672 /* windows doesn't validate these, either, just makes sure the top byte is
1673 cleared. I assume my ifenum module never gives an index with the top
1674 byte set. */
1675 TRACE("returning %d\n", IfIndex);
1676 return IfIndex;
1680 /******************************************************************
1681 * GetIfEntry (IPHLPAPI.@)
1683 * Get information about an interface.
1685 * PARAMS
1686 * pIfRow [In/Out] In: dwIndex of MIB_IFROW selects the interface.
1687 * Out: interface information
1689 * RETURNS
1690 * Success: NO_ERROR
1691 * Failure: error code from winerror.h
1693 DWORD WINAPI GetIfEntry(PMIB_IFROW pIfRow)
1695 DWORD ret;
1696 char nameBuf[MAX_ADAPTER_NAME];
1697 char *name;
1699 TRACE("pIfRow %p\n", pIfRow);
1700 if (!pIfRow)
1701 return ERROR_INVALID_PARAMETER;
1703 name = getInterfaceNameByIndex(pIfRow->dwIndex, nameBuf);
1704 if (name) {
1705 ret = getInterfaceEntryByName(name, pIfRow);
1706 if (ret == NO_ERROR)
1707 ret = getInterfaceStatsByName(name, pIfRow);
1709 else
1710 ret = ERROR_INVALID_DATA;
1711 TRACE("returning %d\n", ret);
1712 return ret;
1715 /******************************************************************
1716 * GetIfEntry2 (IPHLPAPI.@)
1718 DWORD WINAPI GetIfEntry2( MIB_IF_ROW2 *row2 )
1720 DWORD ret, len = sizeof(row2->Description)/sizeof(row2->Description[0]);
1721 char buf[MAX_ADAPTER_NAME], *name;
1722 MIB_IFROW row;
1724 TRACE("%p\n", row2);
1726 if (!row2 || (!(name = getInterfaceNameByIndex( row2->InterfaceIndex, buf )) &&
1727 !(name = getInterfaceNameByIndex( row2->InterfaceLuid.Info.NetLuidIndex, buf ))))
1729 return ERROR_INVALID_PARAMETER;
1731 if ((ret = getInterfaceEntryByName( name, &row ))) return ret;
1732 if ((ret = getInterfaceStatsByName( name, &row ))) return ret;
1734 memset( row2, 0, sizeof(*row2) );
1735 row2->InterfaceLuid.Info.Reserved = 0;
1736 row2->InterfaceLuid.Info.NetLuidIndex = row.dwIndex;
1737 row2->InterfaceLuid.Info.IfType = row.dwType;
1738 row2->InterfaceIndex = row.dwIndex;
1739 row2->InterfaceGuid.Data1 = row.dwIndex;
1740 row2->Type = row.dwType;
1741 row2->Mtu = row.dwMtu;
1742 MultiByteToWideChar( CP_UNIXCP, 0, (const char *)row.bDescr, -1, row2->Description, len );
1743 row2->PhysicalAddressLength = row.dwPhysAddrLen;
1744 memcpy( &row2->PhysicalAddress, &row.bPhysAddr, row.dwPhysAddrLen );
1745 memcpy( &row2->PermanentPhysicalAddress, &row.bPhysAddr, row.dwPhysAddrLen );
1746 row2->OperStatus = IfOperStatusUp;
1747 row2->AdminStatus = NET_IF_ADMIN_STATUS_UP;
1748 row2->MediaConnectState = MediaConnectStateConnected;
1749 row2->ConnectionType = NET_IF_CONNECTION_DEDICATED;
1751 /* stats */
1752 row2->InOctets = row.dwInOctets;
1753 row2->InUcastPkts = row.dwInUcastPkts;
1754 row2->InNUcastPkts = row.dwInNUcastPkts;
1755 row2->InDiscards = row.dwInDiscards;
1756 row2->InErrors = row.dwInErrors;
1757 row2->InUnknownProtos = row.dwInUnknownProtos;
1758 row2->OutOctets = row.dwOutOctets;
1759 row2->OutUcastPkts = row.dwOutUcastPkts;
1760 row2->OutNUcastPkts = row.dwOutNUcastPkts;
1761 row2->OutDiscards = row.dwOutDiscards;
1762 row2->OutErrors = row.dwOutErrors;
1764 return NO_ERROR;
1767 static int IfTableSorter(const void *a, const void *b)
1769 int ret;
1771 if (a && b)
1772 ret = ((const MIB_IFROW*)a)->dwIndex - ((const MIB_IFROW*)b)->dwIndex;
1773 else
1774 ret = 0;
1775 return ret;
1779 /******************************************************************
1780 * GetIfTable (IPHLPAPI.@)
1782 * Get a table of local interfaces.
1784 * PARAMS
1785 * pIfTable [Out] buffer for local interfaces table
1786 * pdwSize [In/Out] length of output buffer
1787 * bOrder [In] whether to sort the table
1789 * RETURNS
1790 * Success: NO_ERROR
1791 * Failure: error code from winerror.h
1793 * NOTES
1794 * If pdwSize is less than required, the function will return
1795 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
1796 * size.
1797 * If bOrder is true, the returned table will be sorted by interface index.
1799 DWORD WINAPI GetIfTable(PMIB_IFTABLE pIfTable, PULONG pdwSize, BOOL bOrder)
1801 DWORD ret;
1803 TRACE("pIfTable %p, pdwSize %p, bOrder %d\n", pdwSize, pdwSize,
1804 (DWORD)bOrder);
1805 if (!pdwSize)
1806 ret = ERROR_INVALID_PARAMETER;
1807 else {
1808 DWORD numInterfaces = get_interface_indices( FALSE, NULL );
1809 ULONG size = sizeof(MIB_IFTABLE);
1811 if (numInterfaces > 1)
1812 size += (numInterfaces - 1) * sizeof(MIB_IFROW);
1813 if (!pIfTable || *pdwSize < size) {
1814 *pdwSize = size;
1815 ret = ERROR_INSUFFICIENT_BUFFER;
1817 else {
1818 InterfaceIndexTable *table;
1819 get_interface_indices( FALSE, &table );
1821 if (table) {
1822 size = sizeof(MIB_IFTABLE);
1823 if (table->numIndexes > 1)
1824 size += (table->numIndexes - 1) * sizeof(MIB_IFROW);
1825 if (*pdwSize < size) {
1826 *pdwSize = size;
1827 ret = ERROR_INSUFFICIENT_BUFFER;
1829 else {
1830 DWORD ndx;
1832 *pdwSize = size;
1833 pIfTable->dwNumEntries = 0;
1834 for (ndx = 0; ndx < table->numIndexes; ndx++) {
1835 pIfTable->table[ndx].dwIndex = table->indexes[ndx];
1836 GetIfEntry(&pIfTable->table[ndx]);
1837 pIfTable->dwNumEntries++;
1839 if (bOrder)
1840 qsort(pIfTable->table, pIfTable->dwNumEntries, sizeof(MIB_IFROW),
1841 IfTableSorter);
1842 ret = NO_ERROR;
1844 HeapFree(GetProcessHeap(), 0, table);
1846 else
1847 ret = ERROR_OUTOFMEMORY;
1850 TRACE("returning %d\n", ret);
1851 return ret;
1854 /******************************************************************
1855 * GetIfTable2 (IPHLPAPI.@)
1857 DWORD WINAPI GetIfTable2( MIB_IF_TABLE2 **table )
1859 DWORD i, nb_interfaces, size = sizeof(MIB_IF_TABLE2);
1860 InterfaceIndexTable *index_table;
1861 MIB_IF_TABLE2 *ret;
1863 TRACE( "table %p\n", table );
1865 if (!table) return ERROR_INVALID_PARAMETER;
1867 if ((nb_interfaces = get_interface_indices( FALSE, NULL )) > 1)
1868 size += (nb_interfaces - 1) * sizeof(MIB_IF_ROW2);
1870 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return ERROR_OUTOFMEMORY;
1872 get_interface_indices( FALSE, &index_table );
1873 if (!index_table)
1875 HeapFree( GetProcessHeap(), 0, ret );
1876 return ERROR_OUTOFMEMORY;
1879 ret->NumEntries = 0;
1880 for (i = 0; i < index_table->numIndexes; i++)
1882 ret->Table[i].InterfaceIndex = index_table->indexes[i];
1883 GetIfEntry2( &ret->Table[i] );
1884 ret->NumEntries++;
1887 HeapFree( GetProcessHeap(), 0, index_table );
1888 *table = ret;
1889 return NO_ERROR;
1892 /******************************************************************
1893 * GetInterfaceInfo (IPHLPAPI.@)
1895 * Get a list of network interface adapters.
1897 * PARAMS
1898 * pIfTable [Out] buffer for interface adapters
1899 * dwOutBufLen [Out] if buffer is too small, returns required size
1901 * RETURNS
1902 * Success: NO_ERROR
1903 * Failure: error code from winerror.h
1905 * BUGS
1906 * MSDN states this should return non-loopback interfaces only.
1908 DWORD WINAPI GetInterfaceInfo(PIP_INTERFACE_INFO pIfTable, PULONG dwOutBufLen)
1910 DWORD ret;
1912 TRACE("pIfTable %p, dwOutBufLen %p\n", pIfTable, dwOutBufLen);
1913 if (!dwOutBufLen)
1914 ret = ERROR_INVALID_PARAMETER;
1915 else {
1916 DWORD numInterfaces = get_interface_indices( FALSE, NULL );
1917 ULONG size = sizeof(IP_INTERFACE_INFO);
1919 if (numInterfaces > 1)
1920 size += (numInterfaces - 1) * sizeof(IP_ADAPTER_INDEX_MAP);
1921 if (!pIfTable || *dwOutBufLen < size) {
1922 *dwOutBufLen = size;
1923 ret = ERROR_INSUFFICIENT_BUFFER;
1925 else {
1926 InterfaceIndexTable *table;
1927 get_interface_indices( FALSE, &table );
1929 if (table) {
1930 size = sizeof(IP_INTERFACE_INFO);
1931 if (table->numIndexes > 1)
1932 size += (table->numIndexes - 1) * sizeof(IP_ADAPTER_INDEX_MAP);
1933 if (*dwOutBufLen < size) {
1934 *dwOutBufLen = size;
1935 ret = ERROR_INSUFFICIENT_BUFFER;
1937 else {
1938 DWORD ndx;
1939 char nameBuf[MAX_ADAPTER_NAME];
1941 *dwOutBufLen = size;
1942 pIfTable->NumAdapters = 0;
1943 for (ndx = 0; ndx < table->numIndexes; ndx++) {
1944 const char *walker, *name;
1945 WCHAR *assigner;
1947 pIfTable->Adapter[ndx].Index = table->indexes[ndx];
1948 name = getInterfaceNameByIndex(table->indexes[ndx], nameBuf);
1949 for (walker = name, assigner = pIfTable->Adapter[ndx].Name;
1950 walker && *walker &&
1951 assigner - pIfTable->Adapter[ndx].Name < MAX_ADAPTER_NAME - 1;
1952 walker++, assigner++)
1953 *assigner = *walker;
1954 *assigner = 0;
1955 pIfTable->NumAdapters++;
1957 ret = NO_ERROR;
1959 HeapFree(GetProcessHeap(), 0, table);
1961 else
1962 ret = ERROR_OUTOFMEMORY;
1965 TRACE("returning %d\n", ret);
1966 return ret;
1970 /******************************************************************
1971 * GetIpAddrTable (IPHLPAPI.@)
1973 * Get interface-to-IP address mapping table.
1975 * PARAMS
1976 * pIpAddrTable [Out] buffer for mapping table
1977 * pdwSize [In/Out] length of output buffer
1978 * bOrder [In] whether to sort the table
1980 * RETURNS
1981 * Success: NO_ERROR
1982 * Failure: error code from winerror.h
1984 * NOTES
1985 * If pdwSize is less than required, the function will return
1986 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
1987 * size.
1988 * If bOrder is true, the returned table will be sorted by the next hop and
1989 * an assortment of arbitrary parameters.
1991 DWORD WINAPI GetIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder)
1993 DWORD ret;
1995 TRACE("pIpAddrTable %p, pdwSize %p, bOrder %d\n", pIpAddrTable, pdwSize,
1996 (DWORD)bOrder);
1997 if (!pdwSize)
1998 ret = ERROR_INVALID_PARAMETER;
1999 else {
2000 PMIB_IPADDRTABLE table;
2002 ret = getIPAddrTable(&table, GetProcessHeap(), 0);
2003 if (ret == NO_ERROR)
2005 ULONG size = FIELD_OFFSET(MIB_IPADDRTABLE, table[table->dwNumEntries]);
2007 if (!pIpAddrTable || *pdwSize < size) {
2008 *pdwSize = size;
2009 ret = ERROR_INSUFFICIENT_BUFFER;
2011 else {
2012 *pdwSize = size;
2013 memcpy(pIpAddrTable, table, size);
2014 /* sort by numeric IP value */
2015 if (bOrder)
2016 qsort(pIpAddrTable->table, pIpAddrTable->dwNumEntries,
2017 sizeof(MIB_IPADDRROW), IpAddrTableNumericSorter);
2018 /* sort ensuring loopback interfaces are in the end */
2019 else
2020 qsort(pIpAddrTable->table, pIpAddrTable->dwNumEntries,
2021 sizeof(MIB_IPADDRROW), IpAddrTableLoopbackSorter);
2022 ret = NO_ERROR;
2024 HeapFree(GetProcessHeap(), 0, table);
2027 TRACE("returning %d\n", ret);
2028 return ret;
2032 /******************************************************************
2033 * GetIpForwardTable (IPHLPAPI.@)
2035 * Get the route table.
2037 * PARAMS
2038 * pIpForwardTable [Out] buffer for route table
2039 * pdwSize [In/Out] length of output buffer
2040 * bOrder [In] whether to sort the table
2042 * RETURNS
2043 * Success: NO_ERROR
2044 * Failure: error code from winerror.h
2046 * NOTES
2047 * If pdwSize is less than required, the function will return
2048 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
2049 * size.
2050 * If bOrder is true, the returned table will be sorted by the next hop and
2051 * an assortment of arbitrary parameters.
2053 DWORD WINAPI GetIpForwardTable(PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, BOOL bOrder)
2055 DWORD ret;
2056 PMIB_IPFORWARDTABLE table;
2058 TRACE("pIpForwardTable %p, pdwSize %p, bOrder %d\n", pIpForwardTable, pdwSize, bOrder);
2060 if (!pdwSize) return ERROR_INVALID_PARAMETER;
2062 ret = AllocateAndGetIpForwardTableFromStack(&table, bOrder, GetProcessHeap(), 0);
2063 if (!ret) {
2064 DWORD size = FIELD_OFFSET( MIB_IPFORWARDTABLE, table[table->dwNumEntries] );
2065 if (!pIpForwardTable || *pdwSize < size) {
2066 *pdwSize = size;
2067 ret = ERROR_INSUFFICIENT_BUFFER;
2069 else {
2070 *pdwSize = size;
2071 memcpy(pIpForwardTable, table, size);
2073 HeapFree(GetProcessHeap(), 0, table);
2075 TRACE("returning %d\n", ret);
2076 return ret;
2080 /******************************************************************
2081 * GetIpNetTable (IPHLPAPI.@)
2083 * Get the IP-to-physical address mapping table.
2085 * PARAMS
2086 * pIpNetTable [Out] buffer for mapping table
2087 * pdwSize [In/Out] length of output buffer
2088 * bOrder [In] whether to sort the table
2090 * RETURNS
2091 * Success: NO_ERROR
2092 * Failure: error code from winerror.h
2094 * NOTES
2095 * If pdwSize is less than required, the function will return
2096 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
2097 * size.
2098 * If bOrder is true, the returned table will be sorted by IP address.
2100 DWORD WINAPI GetIpNetTable(PMIB_IPNETTABLE pIpNetTable, PULONG pdwSize, BOOL bOrder)
2102 DWORD ret;
2103 PMIB_IPNETTABLE table;
2105 TRACE("pIpNetTable %p, pdwSize %p, bOrder %d\n", pIpNetTable, pdwSize, bOrder);
2107 if (!pdwSize) return ERROR_INVALID_PARAMETER;
2109 ret = AllocateAndGetIpNetTableFromStack( &table, bOrder, GetProcessHeap(), 0 );
2110 if (!ret) {
2111 DWORD size = FIELD_OFFSET( MIB_IPNETTABLE, table[table->dwNumEntries] );
2112 if (!pIpNetTable || *pdwSize < size) {
2113 *pdwSize = size;
2114 ret = ERROR_INSUFFICIENT_BUFFER;
2116 else {
2117 *pdwSize = size;
2118 memcpy(pIpNetTable, table, size);
2120 HeapFree(GetProcessHeap(), 0, table);
2122 TRACE("returning %d\n", ret);
2123 return ret;
2126 /* Gets the DNS server list into the list beginning at list. Assumes that
2127 * a single server address may be placed at list if *len is at least
2128 * sizeof(IP_ADDR_STRING) long. Otherwise, list->Next is set to firstDynamic,
2129 * and assumes that all remaining DNS servers are contiguously located
2130 * beginning at firstDynamic. On input, *len is assumed to be the total number
2131 * of bytes available for all DNS servers, and is ignored if list is NULL.
2132 * On return, *len is set to the total number of bytes required for all DNS
2133 * servers.
2134 * Returns ERROR_BUFFER_OVERFLOW if *len is insufficient,
2135 * ERROR_SUCCESS otherwise.
2137 static DWORD get_dns_server_list(PIP_ADDR_STRING list,
2138 PIP_ADDR_STRING firstDynamic, DWORD *len)
2140 DWORD size;
2141 int num = get_dns_servers( NULL, 0, TRUE );
2143 size = num * sizeof(IP_ADDR_STRING);
2144 if (!list || *len < size) {
2145 *len = size;
2146 return ERROR_BUFFER_OVERFLOW;
2148 *len = size;
2149 if (num > 0) {
2150 PIP_ADDR_STRING ptr;
2151 int i;
2152 SOCKADDR_STORAGE *addr = HeapAlloc( GetProcessHeap(), 0, num * sizeof(SOCKADDR_STORAGE) );
2154 get_dns_servers( addr, num, TRUE );
2156 for (i = 0, ptr = list; i < num; i++, ptr = ptr->Next) {
2157 toIPAddressString(((struct sockaddr_in *)(addr + i))->sin_addr.s_addr,
2158 ptr->IpAddress.String);
2159 if (i == num - 1)
2160 ptr->Next = NULL;
2161 else if (i == 0)
2162 ptr->Next = firstDynamic;
2163 else
2164 ptr->Next = (PIP_ADDR_STRING)((PBYTE)ptr + sizeof(IP_ADDR_STRING));
2166 HeapFree( GetProcessHeap(), 0, addr );
2168 return ERROR_SUCCESS;
2171 /******************************************************************
2172 * GetNetworkParams (IPHLPAPI.@)
2174 * Get the network parameters for the local computer.
2176 * PARAMS
2177 * pFixedInfo [Out] buffer for network parameters
2178 * pOutBufLen [In/Out] length of output buffer
2180 * RETURNS
2181 * Success: NO_ERROR
2182 * Failure: error code from winerror.h
2184 * NOTES
2185 * If pOutBufLen is less than required, the function will return
2186 * ERROR_INSUFFICIENT_BUFFER, and pOutBufLen will be set to the required byte
2187 * size.
2189 DWORD WINAPI GetNetworkParams(PFIXED_INFO pFixedInfo, PULONG pOutBufLen)
2191 DWORD ret, size, serverListSize;
2192 LONG regReturn;
2193 HKEY hKey;
2195 TRACE("pFixedInfo %p, pOutBufLen %p\n", pFixedInfo, pOutBufLen);
2196 if (!pOutBufLen)
2197 return ERROR_INVALID_PARAMETER;
2199 get_dns_server_list(NULL, NULL, &serverListSize);
2200 size = sizeof(FIXED_INFO) + serverListSize - sizeof(IP_ADDR_STRING);
2201 if (!pFixedInfo || *pOutBufLen < size) {
2202 *pOutBufLen = size;
2203 return ERROR_BUFFER_OVERFLOW;
2206 memset(pFixedInfo, 0, size);
2207 size = sizeof(pFixedInfo->HostName);
2208 GetComputerNameExA(ComputerNameDnsHostname, pFixedInfo->HostName, &size);
2209 size = sizeof(pFixedInfo->DomainName);
2210 GetComputerNameExA(ComputerNameDnsDomain, pFixedInfo->DomainName, &size);
2211 get_dns_server_list(&pFixedInfo->DnsServerList,
2212 (PIP_ADDR_STRING)((BYTE *)pFixedInfo + sizeof(FIXED_INFO)),
2213 &serverListSize);
2214 /* Assume the first DNS server in the list is the "current" DNS server: */
2215 pFixedInfo->CurrentDnsServer = &pFixedInfo->DnsServerList;
2216 pFixedInfo->NodeType = HYBRID_NODETYPE;
2217 regReturn = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
2218 "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_READ, &hKey);
2219 if (regReturn != ERROR_SUCCESS)
2220 regReturn = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
2221 "SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters", 0, KEY_READ,
2222 &hKey);
2223 if (regReturn == ERROR_SUCCESS)
2225 DWORD size = sizeof(pFixedInfo->ScopeId);
2227 RegQueryValueExA(hKey, "ScopeID", NULL, NULL, (LPBYTE)pFixedInfo->ScopeId, &size);
2228 RegCloseKey(hKey);
2231 /* FIXME: can check whether routing's enabled in /proc/sys/net/ipv4/ip_forward
2232 I suppose could also check for a listener on port 53 to set EnableDns */
2233 ret = NO_ERROR;
2234 TRACE("returning %d\n", ret);
2235 return ret;
2239 /******************************************************************
2240 * GetNumberOfInterfaces (IPHLPAPI.@)
2242 * Get the number of interfaces.
2244 * PARAMS
2245 * pdwNumIf [Out] number of interfaces
2247 * RETURNS
2248 * NO_ERROR on success, ERROR_INVALID_PARAMETER if pdwNumIf is NULL.
2250 DWORD WINAPI GetNumberOfInterfaces(PDWORD pdwNumIf)
2252 DWORD ret;
2254 TRACE("pdwNumIf %p\n", pdwNumIf);
2255 if (!pdwNumIf)
2256 ret = ERROR_INVALID_PARAMETER;
2257 else {
2258 *pdwNumIf = get_interface_indices( FALSE, NULL );
2259 ret = NO_ERROR;
2261 TRACE("returning %d\n", ret);
2262 return ret;
2266 /******************************************************************
2267 * GetPerAdapterInfo (IPHLPAPI.@)
2269 * Get information about an adapter corresponding to an interface.
2271 * PARAMS
2272 * IfIndex [In] interface info
2273 * pPerAdapterInfo [Out] buffer for per adapter info
2274 * pOutBufLen [In/Out] length of output buffer
2276 * RETURNS
2277 * Success: NO_ERROR
2278 * Failure: error code from winerror.h
2280 DWORD WINAPI GetPerAdapterInfo(ULONG IfIndex, PIP_PER_ADAPTER_INFO pPerAdapterInfo, PULONG pOutBufLen)
2282 ULONG bytesNeeded = sizeof(IP_PER_ADAPTER_INFO), serverListSize = 0;
2283 DWORD ret = NO_ERROR;
2285 TRACE("(IfIndex %d, pPerAdapterInfo %p, pOutBufLen %p)\n", IfIndex, pPerAdapterInfo, pOutBufLen);
2287 if (!pOutBufLen) return ERROR_INVALID_PARAMETER;
2289 if (!isIfIndexLoopback(IfIndex)) {
2290 get_dns_server_list(NULL, NULL, &serverListSize);
2291 if (serverListSize > sizeof(IP_ADDR_STRING))
2292 bytesNeeded += serverListSize - sizeof(IP_ADDR_STRING);
2294 if (!pPerAdapterInfo || *pOutBufLen < bytesNeeded)
2296 *pOutBufLen = bytesNeeded;
2297 return ERROR_BUFFER_OVERFLOW;
2300 memset(pPerAdapterInfo, 0, bytesNeeded);
2301 if (!isIfIndexLoopback(IfIndex)) {
2302 ret = get_dns_server_list(&pPerAdapterInfo->DnsServerList,
2303 (PIP_ADDR_STRING)((PBYTE)pPerAdapterInfo + sizeof(IP_PER_ADAPTER_INFO)),
2304 &serverListSize);
2305 /* Assume the first DNS server in the list is the "current" DNS server: */
2306 pPerAdapterInfo->CurrentDnsServer = &pPerAdapterInfo->DnsServerList;
2308 return ret;
2312 /******************************************************************
2313 * GetRTTAndHopCount (IPHLPAPI.@)
2315 * Get round-trip time (RTT) and hop count.
2317 * PARAMS
2319 * DestIpAddress [In] destination address to get the info for
2320 * HopCount [Out] retrieved hop count
2321 * MaxHops [In] maximum hops to search for the destination
2322 * RTT [Out] RTT in milliseconds
2324 * RETURNS
2325 * Success: TRUE
2326 * Failure: FALSE
2328 * FIXME
2329 * Stub, returns FALSE.
2331 BOOL WINAPI GetRTTAndHopCount(IPAddr DestIpAddress, PULONG HopCount, ULONG MaxHops, PULONG RTT)
2333 FIXME("(DestIpAddress 0x%08x, HopCount %p, MaxHops %d, RTT %p): stub\n",
2334 DestIpAddress, HopCount, MaxHops, RTT);
2335 return FALSE;
2339 /******************************************************************
2340 * GetTcpTable (IPHLPAPI.@)
2342 * Get the table of active TCP connections.
2344 * PARAMS
2345 * pTcpTable [Out] buffer for TCP connections table
2346 * pdwSize [In/Out] length of output buffer
2347 * bOrder [In] whether to order the table
2349 * RETURNS
2350 * Success: NO_ERROR
2351 * Failure: error code from winerror.h
2353 * NOTES
2354 * If pdwSize is less than required, the function will return
2355 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to
2356 * the required byte size.
2357 * If bOrder is true, the returned table will be sorted, first by
2358 * local address and port number, then by remote address and port
2359 * number.
2361 DWORD WINAPI GetTcpTable(PMIB_TCPTABLE pTcpTable, PDWORD pdwSize, BOOL bOrder)
2363 TRACE("pTcpTable %p, pdwSize %p, bOrder %d\n", pTcpTable, pdwSize, bOrder);
2364 return GetExtendedTcpTable(pTcpTable, pdwSize, bOrder, WS_AF_INET, TCP_TABLE_BASIC_ALL, 0);
2367 /******************************************************************
2368 * GetExtendedTcpTable (IPHLPAPI.@)
2370 DWORD WINAPI GetExtendedTcpTable(PVOID pTcpTable, PDWORD pdwSize, BOOL bOrder,
2371 ULONG ulAf, TCP_TABLE_CLASS TableClass, ULONG Reserved)
2373 DWORD ret, size;
2374 void *table;
2376 TRACE("pTcpTable %p, pdwSize %p, bOrder %d, ulAf %u, TableClass %u, Reserved %u\n",
2377 pTcpTable, pdwSize, bOrder, ulAf, TableClass, Reserved);
2379 if (!pdwSize) return ERROR_INVALID_PARAMETER;
2381 if (ulAf != WS_AF_INET)
2383 FIXME("ulAf = %u not supported\n", ulAf);
2384 return ERROR_NOT_SUPPORTED;
2386 if (TableClass >= TCP_TABLE_OWNER_MODULE_LISTENER)
2387 FIXME("module classes not fully supported\n");
2389 if ((ret = build_tcp_table(TableClass, &table, bOrder, GetProcessHeap(), 0, &size)))
2390 return ret;
2392 if (!pTcpTable || *pdwSize < size)
2394 *pdwSize = size;
2395 ret = ERROR_INSUFFICIENT_BUFFER;
2397 else
2399 *pdwSize = size;
2400 memcpy(pTcpTable, table, size);
2402 HeapFree(GetProcessHeap(), 0, table);
2403 return ret;
2406 /******************************************************************
2407 * GetUdpTable (IPHLPAPI.@)
2409 * Get a table of active UDP connections.
2411 * PARAMS
2412 * pUdpTable [Out] buffer for UDP connections table
2413 * pdwSize [In/Out] length of output buffer
2414 * bOrder [In] whether to order the table
2416 * RETURNS
2417 * Success: NO_ERROR
2418 * Failure: error code from winerror.h
2420 * NOTES
2421 * If pdwSize is less than required, the function will return
2422 * ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the
2423 * required byte size.
2424 * If bOrder is true, the returned table will be sorted, first by
2425 * local address, then by local port number.
2427 DWORD WINAPI GetUdpTable(PMIB_UDPTABLE pUdpTable, PDWORD pdwSize, BOOL bOrder)
2429 return GetExtendedUdpTable(pUdpTable, pdwSize, bOrder, WS_AF_INET, UDP_TABLE_BASIC, 0);
2432 /******************************************************************
2433 * GetExtendedUdpTable (IPHLPAPI.@)
2435 DWORD WINAPI GetExtendedUdpTable(PVOID pUdpTable, PDWORD pdwSize, BOOL bOrder,
2436 ULONG ulAf, UDP_TABLE_CLASS TableClass, ULONG Reserved)
2438 DWORD ret, size;
2439 void *table;
2441 TRACE("pUdpTable %p, pdwSize %p, bOrder %d, ulAf %u, TableClass %u, Reserved %u\n",
2442 pUdpTable, pdwSize, bOrder, ulAf, TableClass, Reserved);
2444 if (!pdwSize) return ERROR_INVALID_PARAMETER;
2446 if (ulAf != WS_AF_INET)
2448 FIXME("ulAf = %u not supported\n", ulAf);
2449 return ERROR_NOT_SUPPORTED;
2451 if (TableClass == UDP_TABLE_OWNER_MODULE)
2452 FIXME("UDP_TABLE_OWNER_MODULE not fully supported\n");
2454 if ((ret = build_udp_table(TableClass, &table, bOrder, GetProcessHeap(), 0, &size)))
2455 return ret;
2457 if (!pUdpTable || *pdwSize < size)
2459 *pdwSize = size;
2460 ret = ERROR_INSUFFICIENT_BUFFER;
2462 else
2464 *pdwSize = size;
2465 memcpy(pUdpTable, table, size);
2467 HeapFree(GetProcessHeap(), 0, table);
2468 return ret;
2471 DWORD WINAPI GetUnicastIpAddressEntry(MIB_UNICASTIPADDRESS_ROW *row)
2473 IP_ADAPTER_ADDRESSES *aa, *ptr;
2474 ULONG size = 0;
2475 DWORD ret;
2477 TRACE("%p\n", row);
2479 if (!row)
2480 return ERROR_INVALID_PARAMETER;
2482 ret = GetAdaptersAddresses(row->Address.si_family, 0, NULL, NULL, &size);
2483 if (ret != ERROR_BUFFER_OVERFLOW)
2484 return ret;
2485 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size)))
2486 return ERROR_OUTOFMEMORY;
2487 if ((ret = GetAdaptersAddresses(row->Address.si_family, 0, NULL, ptr, &size)))
2489 HeapFree(GetProcessHeap(), 0, ptr);
2490 return ret;
2493 ret = ERROR_FILE_NOT_FOUND;
2494 for (aa = ptr; aa; aa = aa->Next)
2496 IP_ADAPTER_UNICAST_ADDRESS *ua;
2498 if (aa->u.s.IfIndex != row->InterfaceIndex &&
2499 memcmp(&aa->Luid, &row->InterfaceLuid, sizeof(row->InterfaceLuid)))
2500 continue;
2501 ret = ERROR_NOT_FOUND;
2503 ua = aa->FirstUnicastAddress;
2504 while (ua)
2506 SOCKADDR_INET *uaaddr = (SOCKADDR_INET *)ua->Address.lpSockaddr;
2508 if ((row->Address.si_family == WS_AF_INET6 &&
2509 !memcmp(&row->Address.Ipv6.sin6_addr, &uaaddr->Ipv6.sin6_addr, sizeof(uaaddr->Ipv6.sin6_addr))) ||
2510 (row->Address.si_family == WS_AF_INET &&
2511 row->Address.Ipv4.sin_addr.S_un.S_addr == uaaddr->Ipv4.sin_addr.S_un.S_addr))
2513 memcpy(&row->InterfaceLuid, &aa->Luid, sizeof(aa->Luid));
2514 row->InterfaceIndex = aa->u.s.IfIndex;
2515 row->PrefixOrigin = ua->PrefixOrigin;
2516 row->SuffixOrigin = ua->SuffixOrigin;
2517 row->ValidLifetime = ua->ValidLifetime;
2518 row->PreferredLifetime = ua->PreferredLifetime;
2519 row->OnLinkPrefixLength = ua->OnLinkPrefixLength;
2520 row->SkipAsSource = 0;
2521 row->DadState = ua->DadState;
2522 if (row->Address.si_family == WS_AF_INET6)
2523 row->ScopeId.u.Value = row->Address.Ipv6.sin6_scope_id;
2524 else
2525 row->ScopeId.u.Value = 0;
2526 NtQuerySystemTime(&row->CreationTimeStamp);
2527 HeapFree(GetProcessHeap(), 0, ptr);
2528 return NO_ERROR;
2530 ua = ua->Next;
2533 HeapFree(GetProcessHeap(), 0, ptr);
2535 return ret;
2538 DWORD WINAPI GetUnicastIpAddressTable(ADDRESS_FAMILY family, MIB_UNICASTIPADDRESS_TABLE **table)
2540 IP_ADAPTER_ADDRESSES *aa, *ptr;
2541 MIB_UNICASTIPADDRESS_TABLE *data;
2542 DWORD ret, count = 0;
2543 ULONG size, flags;
2545 TRACE("%u, %p\n", family, table);
2547 if (!table || (family != WS_AF_INET && family != WS_AF_INET6 && family != WS_AF_UNSPEC))
2548 return ERROR_INVALID_PARAMETER;
2550 flags = GAA_FLAG_SKIP_ANYCAST |
2551 GAA_FLAG_SKIP_MULTICAST |
2552 GAA_FLAG_SKIP_DNS_SERVER |
2553 GAA_FLAG_SKIP_FRIENDLY_NAME;
2555 ret = GetAdaptersAddresses(family, flags, NULL, NULL, &size);
2556 if (ret != ERROR_BUFFER_OVERFLOW)
2557 return ret;
2558 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size)))
2559 return ERROR_OUTOFMEMORY;
2560 if ((ret = GetAdaptersAddresses(family, flags, NULL, ptr, &size)))
2562 HeapFree(GetProcessHeap(), 0, ptr);
2563 return ret;
2566 for (aa = ptr; aa; aa = aa->Next)
2568 IP_ADAPTER_UNICAST_ADDRESS *ua = aa->FirstUnicastAddress;
2569 while (ua)
2571 count++;
2572 ua = ua->Next;
2576 if (!(data = HeapAlloc(GetProcessHeap(), 0, sizeof(*data) + (count - 1) * sizeof(data->Table[0]))))
2578 HeapFree(GetProcessHeap(), 0, ptr);
2579 return ERROR_OUTOFMEMORY;
2582 data->NumEntries = 0;
2583 for (aa = ptr; aa; aa = aa->Next)
2585 IP_ADAPTER_UNICAST_ADDRESS *ua = aa->FirstUnicastAddress;
2586 while (ua)
2588 MIB_UNICASTIPADDRESS_ROW *row = &data->Table[data->NumEntries];
2589 memcpy(&row->Address, ua->Address.lpSockaddr, ua->Address.iSockaddrLength);
2590 memcpy(&row->InterfaceLuid, &aa->Luid, sizeof(aa->Luid));
2591 row->InterfaceIndex = aa->u.s.IfIndex;
2592 row->PrefixOrigin = ua->PrefixOrigin;
2593 row->SuffixOrigin = ua->SuffixOrigin;
2594 row->ValidLifetime = ua->ValidLifetime;
2595 row->PreferredLifetime = ua->PreferredLifetime;
2596 row->OnLinkPrefixLength = ua->OnLinkPrefixLength;
2597 row->SkipAsSource = 0;
2598 row->DadState = ua->DadState;
2599 if (row->Address.si_family == WS_AF_INET6)
2600 row->ScopeId.u.Value = row->Address.Ipv6.sin6_scope_id;
2601 else
2602 row->ScopeId.u.Value = 0;
2603 NtQuerySystemTime(&row->CreationTimeStamp);
2605 data->NumEntries++;
2606 ua = ua->Next;
2610 HeapFree(GetProcessHeap(), 0, ptr);
2612 *table = data;
2613 return ret;
2616 /******************************************************************
2617 * GetUniDirectionalAdapterInfo (IPHLPAPI.@)
2619 * This is a Win98-only function to get information on "unidirectional"
2620 * adapters. Since this is pretty nonsensical in other contexts, it
2621 * never returns anything.
2623 * PARAMS
2624 * pIPIfInfo [Out] buffer for adapter infos
2625 * dwOutBufLen [Out] length of the output buffer
2627 * RETURNS
2628 * Success: NO_ERROR
2629 * Failure: error code from winerror.h
2631 * FIXME
2632 * Stub, returns ERROR_NOT_SUPPORTED.
2634 DWORD WINAPI GetUniDirectionalAdapterInfo(PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS pIPIfInfo, PULONG dwOutBufLen)
2636 TRACE("pIPIfInfo %p, dwOutBufLen %p\n", pIPIfInfo, dwOutBufLen);
2637 /* a unidirectional adapter?? not bloody likely! */
2638 return ERROR_NOT_SUPPORTED;
2642 /******************************************************************
2643 * IpReleaseAddress (IPHLPAPI.@)
2645 * Release an IP obtained through DHCP,
2647 * PARAMS
2648 * AdapterInfo [In] adapter to release IP address
2650 * RETURNS
2651 * Success: NO_ERROR
2652 * Failure: error code from winerror.h
2654 * NOTES
2655 * Since GetAdaptersInfo never returns adapters that have DHCP enabled,
2656 * this function does nothing.
2658 * FIXME
2659 * Stub, returns ERROR_NOT_SUPPORTED.
2661 DWORD WINAPI IpReleaseAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
2663 FIXME("Stub AdapterInfo %p\n", AdapterInfo);
2664 return ERROR_NOT_SUPPORTED;
2668 /******************************************************************
2669 * IpRenewAddress (IPHLPAPI.@)
2671 * Renew an IP obtained through DHCP.
2673 * PARAMS
2674 * AdapterInfo [In] adapter to renew IP address
2676 * RETURNS
2677 * Success: NO_ERROR
2678 * Failure: error code from winerror.h
2680 * NOTES
2681 * Since GetAdaptersInfo never returns adapters that have DHCP enabled,
2682 * this function does nothing.
2684 * FIXME
2685 * Stub, returns ERROR_NOT_SUPPORTED.
2687 DWORD WINAPI IpRenewAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
2689 FIXME("Stub AdapterInfo %p\n", AdapterInfo);
2690 return ERROR_NOT_SUPPORTED;
2694 /******************************************************************
2695 * NotifyAddrChange (IPHLPAPI.@)
2697 * Notify caller whenever the ip-interface map is changed.
2699 * PARAMS
2700 * Handle [Out] handle usable in asynchronous notification
2701 * overlapped [In] overlapped structure that notifies the caller
2703 * RETURNS
2704 * Success: NO_ERROR
2705 * Failure: error code from winerror.h
2707 * FIXME
2708 * Stub, returns ERROR_NOT_SUPPORTED.
2710 DWORD WINAPI NotifyAddrChange(PHANDLE Handle, LPOVERLAPPED overlapped)
2712 FIXME("(Handle %p, overlapped %p): stub\n", Handle, overlapped);
2713 if (Handle) *Handle = INVALID_HANDLE_VALUE;
2714 if (overlapped) ((IO_STATUS_BLOCK *) overlapped)->u.Status = STATUS_PENDING;
2715 return ERROR_IO_PENDING;
2719 /******************************************************************
2720 * NotifyIpInterfaceChange (IPHLPAPI.@)
2722 DWORD WINAPI NotifyIpInterfaceChange(ADDRESS_FAMILY family, PIPINTERFACE_CHANGE_CALLBACK callback,
2723 PVOID context, BOOLEAN init_notify, PHANDLE handle)
2725 FIXME("(family %d, callback %p, context %p, init_notify %d, handle %p): stub\n",
2726 family, callback, context, init_notify, handle);
2727 if (handle) *handle = NULL;
2728 return ERROR_NOT_SUPPORTED;
2732 /******************************************************************
2733 * NotifyRouteChange (IPHLPAPI.@)
2735 * Notify caller whenever the ip routing table is changed.
2737 * PARAMS
2738 * Handle [Out] handle usable in asynchronous notification
2739 * overlapped [In] overlapped structure that notifies the caller
2741 * RETURNS
2742 * Success: NO_ERROR
2743 * Failure: error code from winerror.h
2745 * FIXME
2746 * Stub, returns ERROR_NOT_SUPPORTED.
2748 DWORD WINAPI NotifyRouteChange(PHANDLE Handle, LPOVERLAPPED overlapped)
2750 FIXME("(Handle %p, overlapped %p): stub\n", Handle, overlapped);
2751 return ERROR_NOT_SUPPORTED;
2755 /******************************************************************
2756 * NotifyUnicastIpAddressChange (IPHLPAPI.@)
2758 DWORD WINAPI NotifyUnicastIpAddressChange(ADDRESS_FAMILY family, PUNICAST_IPADDRESS_CHANGE_CALLBACK callback,
2759 PVOID context, BOOLEAN init_notify, PHANDLE handle)
2761 FIXME("(family %d, callback %p, context %p, init_notify %d, handle %p): stub\n",
2762 family, callback, context, init_notify, handle);
2763 if (handle) *handle = NULL;
2764 return ERROR_NOT_SUPPORTED;
2767 /******************************************************************
2768 * SendARP (IPHLPAPI.@)
2770 * Send an ARP request.
2772 * PARAMS
2773 * DestIP [In] attempt to obtain this IP
2774 * SrcIP [In] optional sender IP address
2775 * pMacAddr [Out] buffer for the mac address
2776 * PhyAddrLen [In/Out] length of the output buffer
2778 * RETURNS
2779 * Success: NO_ERROR
2780 * Failure: error code from winerror.h
2782 * FIXME
2783 * Stub, returns ERROR_NOT_SUPPORTED.
2785 DWORD WINAPI SendARP(IPAddr DestIP, IPAddr SrcIP, PULONG pMacAddr, PULONG PhyAddrLen)
2787 FIXME("(DestIP 0x%08x, SrcIP 0x%08x, pMacAddr %p, PhyAddrLen %p): stub\n",
2788 DestIP, SrcIP, pMacAddr, PhyAddrLen);
2789 return ERROR_NOT_SUPPORTED;
2793 /******************************************************************
2794 * SetIfEntry (IPHLPAPI.@)
2796 * Set the administrative status of an interface.
2798 * PARAMS
2799 * pIfRow [In] dwAdminStatus member specifies the new status.
2801 * RETURNS
2802 * Success: NO_ERROR
2803 * Failure: error code from winerror.h
2805 * FIXME
2806 * Stub, returns ERROR_NOT_SUPPORTED.
2808 DWORD WINAPI SetIfEntry(PMIB_IFROW pIfRow)
2810 FIXME("(pIfRow %p): stub\n", pIfRow);
2811 /* this is supposed to set an interface administratively up or down.
2812 Could do SIOCSIFFLAGS and set/clear IFF_UP, but, not sure I want to, and
2813 this sort of down is indistinguishable from other sorts of down (e.g. no
2814 link). */
2815 return ERROR_NOT_SUPPORTED;
2819 /******************************************************************
2820 * SetIpForwardEntry (IPHLPAPI.@)
2822 * Modify an existing route.
2824 * PARAMS
2825 * pRoute [In] route with the new information
2827 * RETURNS
2828 * Success: NO_ERROR
2829 * Failure: error code from winerror.h
2831 * FIXME
2832 * Stub, returns NO_ERROR.
2834 DWORD WINAPI SetIpForwardEntry(PMIB_IPFORWARDROW pRoute)
2836 FIXME("(pRoute %p): stub\n", pRoute);
2837 /* this is to add a route entry, how's it distinguishable from
2838 CreateIpForwardEntry?
2839 could use SIOCADDRT, not sure I want to */
2840 return 0;
2844 /******************************************************************
2845 * SetIpNetEntry (IPHLPAPI.@)
2847 * Modify an existing ARP entry.
2849 * PARAMS
2850 * pArpEntry [In] ARP entry with the new information
2852 * RETURNS
2853 * Success: NO_ERROR
2854 * Failure: error code from winerror.h
2856 * FIXME
2857 * Stub, returns NO_ERROR.
2859 DWORD WINAPI SetIpNetEntry(PMIB_IPNETROW pArpEntry)
2861 FIXME("(pArpEntry %p): stub\n", pArpEntry);
2862 /* same as CreateIpNetEntry here, could use SIOCSARP, not sure I want to */
2863 return 0;
2867 /******************************************************************
2868 * SetIpStatistics (IPHLPAPI.@)
2870 * Toggle IP forwarding and det the default TTL value.
2872 * PARAMS
2873 * pIpStats [In] IP statistics with the new information
2875 * RETURNS
2876 * Success: NO_ERROR
2877 * Failure: error code from winerror.h
2879 * FIXME
2880 * Stub, returns NO_ERROR.
2882 DWORD WINAPI SetIpStatistics(PMIB_IPSTATS pIpStats)
2884 FIXME("(pIpStats %p): stub\n", pIpStats);
2885 return 0;
2889 /******************************************************************
2890 * SetIpTTL (IPHLPAPI.@)
2892 * Set the default TTL value.
2894 * PARAMS
2895 * nTTL [In] new TTL value
2897 * RETURNS
2898 * Success: NO_ERROR
2899 * Failure: error code from winerror.h
2901 * FIXME
2902 * Stub, returns NO_ERROR.
2904 DWORD WINAPI SetIpTTL(UINT nTTL)
2906 FIXME("(nTTL %d): stub\n", nTTL);
2907 /* could echo nTTL > /proc/net/sys/net/ipv4/ip_default_ttl, not sure I
2908 want to. Could map EACCESS to ERROR_ACCESS_DENIED, I suppose */
2909 return 0;
2913 /******************************************************************
2914 * SetTcpEntry (IPHLPAPI.@)
2916 * Set the state of a TCP connection.
2918 * PARAMS
2919 * pTcpRow [In] specifies connection with new state
2921 * RETURNS
2922 * Success: NO_ERROR
2923 * Failure: error code from winerror.h
2925 * FIXME
2926 * Stub, returns NO_ERROR.
2928 DWORD WINAPI SetTcpEntry(PMIB_TCPROW pTcpRow)
2930 FIXME("(pTcpRow %p): stub\n", pTcpRow);
2931 return 0;
2934 /******************************************************************
2935 * SetPerTcpConnectionEStats (IPHLPAPI.@)
2937 DWORD WINAPI SetPerTcpConnectionEStats(PMIB_TCPROW row, TCP_ESTATS_TYPE state, PBYTE rw,
2938 ULONG version, ULONG size, ULONG offset)
2940 FIXME("(row %p, state %d, rw %p, version %u, size %u, offset %u): stub\n",
2941 row, state, rw, version, size, offset);
2942 return ERROR_NOT_SUPPORTED;
2946 /******************************************************************
2947 * UnenableRouter (IPHLPAPI.@)
2949 * Decrement the IP-forwarding reference count. Turn off IP-forwarding
2950 * if it reaches zero.
2952 * PARAMS
2953 * pOverlapped [In/Out] should be the same as in EnableRouter()
2954 * lpdwEnableCount [Out] optional, receives reference count
2956 * RETURNS
2957 * Success: NO_ERROR
2958 * Failure: error code from winerror.h
2960 * FIXME
2961 * Stub, returns ERROR_NOT_SUPPORTED.
2963 DWORD WINAPI UnenableRouter(OVERLAPPED * pOverlapped, LPDWORD lpdwEnableCount)
2965 FIXME("(pOverlapped %p, lpdwEnableCount %p): stub\n", pOverlapped,
2966 lpdwEnableCount);
2967 /* could echo "0" > /proc/net/sys/net/ipv4/ip_forward, not sure I want to
2968 could map EACCESS to ERROR_ACCESS_DENIED, I suppose
2970 return ERROR_NOT_SUPPORTED;
2973 /******************************************************************
2974 * PfCreateInterface (IPHLPAPI.@)
2976 DWORD WINAPI PfCreateInterface(DWORD dwName, PFFORWARD_ACTION inAction, PFFORWARD_ACTION outAction,
2977 BOOL bUseLog, BOOL bMustBeUnique, INTERFACE_HANDLE *ppInterface)
2979 FIXME("(%d %d %d %x %x %p) stub\n", dwName, inAction, outAction, bUseLog, bMustBeUnique, ppInterface);
2980 return ERROR_CALL_NOT_IMPLEMENTED;
2983 /******************************************************************
2984 * PfUnBindInterface (IPHLPAPI.@)
2986 DWORD WINAPI PfUnBindInterface(INTERFACE_HANDLE interface)
2988 FIXME("(%p) stub\n", interface);
2989 return ERROR_CALL_NOT_IMPLEMENTED;
2992 /******************************************************************
2993 * PfDeleteInterface(IPHLPAPI.@)
2995 DWORD WINAPI PfDeleteInterface(INTERFACE_HANDLE interface)
2997 FIXME("(%p) stub\n", interface);
2998 return ERROR_CALL_NOT_IMPLEMENTED;
3001 /******************************************************************
3002 * PfBindInterfaceToIPAddress(IPHLPAPI.@)
3004 DWORD WINAPI PfBindInterfaceToIPAddress(INTERFACE_HANDLE interface, PFADDRESSTYPE type, PBYTE ip)
3006 FIXME("(%p %d %p) stub\n", interface, type, ip);
3007 return ERROR_CALL_NOT_IMPLEMENTED;
3010 /******************************************************************
3011 * GetTcpTable2 (IPHLPAPI.@)
3013 ULONG WINAPI GetTcpTable2(PMIB_TCPTABLE2 table, PULONG size, BOOL order)
3015 FIXME("pTcpTable2 %p, pdwSize %p, bOrder %d: stub\n", table, size, order);
3016 return ERROR_NOT_SUPPORTED;
3019 /******************************************************************
3020 * GetTcp6Table (IPHLPAPI.@)
3022 ULONG WINAPI GetTcp6Table(PMIB_TCP6TABLE table, PULONG size, BOOL order)
3024 FIXME("pTcp6Table %p, size %p, order %d: stub\n", table, size, order);
3025 return ERROR_NOT_SUPPORTED;
3028 /******************************************************************
3029 * GetTcp6Table2 (IPHLPAPI.@)
3031 ULONG WINAPI GetTcp6Table2(PMIB_TCP6TABLE2 table, PULONG size, BOOL order)
3033 FIXME("pTcp6Table2 %p, size %p, order %d: stub\n", table, size, order);
3034 return ERROR_NOT_SUPPORTED;
3037 /******************************************************************
3038 * ConvertInterfaceGuidToLuid (IPHLPAPI.@)
3040 DWORD WINAPI ConvertInterfaceGuidToLuid(const GUID *guid, NET_LUID *luid)
3042 DWORD ret;
3043 MIB_IFROW row;
3045 TRACE("(%s %p)\n", debugstr_guid(guid), luid);
3047 if (!guid || !luid) return ERROR_INVALID_PARAMETER;
3049 row.dwIndex = guid->Data1;
3050 if ((ret = GetIfEntry( &row ))) return ret;
3052 luid->Info.Reserved = 0;
3053 luid->Info.NetLuidIndex = guid->Data1;
3054 luid->Info.IfType = row.dwType;
3055 return NO_ERROR;
3058 /******************************************************************
3059 * ConvertInterfaceIndexToLuid (IPHLPAPI.@)
3061 DWORD WINAPI ConvertInterfaceIndexToLuid(NET_IFINDEX index, NET_LUID *luid)
3063 MIB_IFROW row;
3065 TRACE("(%u %p)\n", index, luid);
3067 if (!luid) return ERROR_INVALID_PARAMETER;
3068 memset( luid, 0, sizeof(*luid) );
3070 row.dwIndex = index;
3071 if (GetIfEntry( &row )) return ERROR_FILE_NOT_FOUND;
3073 luid->Info.Reserved = 0;
3074 luid->Info.NetLuidIndex = index;
3075 luid->Info.IfType = row.dwType;
3076 return NO_ERROR;
3079 /******************************************************************
3080 * ConvertInterfaceLuidToGuid (IPHLPAPI.@)
3082 DWORD WINAPI ConvertInterfaceLuidToGuid(const NET_LUID *luid, GUID *guid)
3084 DWORD ret;
3085 MIB_IFROW row;
3087 TRACE("(%p %p)\n", luid, guid);
3089 if (!luid || !guid) return ERROR_INVALID_PARAMETER;
3091 row.dwIndex = luid->Info.NetLuidIndex;
3092 if ((ret = GetIfEntry( &row ))) return ret;
3094 memset( guid, 0, sizeof(*guid) );
3095 guid->Data1 = luid->Info.NetLuidIndex;
3096 return NO_ERROR;
3099 /******************************************************************
3100 * ConvertInterfaceLuidToIndex (IPHLPAPI.@)
3102 DWORD WINAPI ConvertInterfaceLuidToIndex(const NET_LUID *luid, NET_IFINDEX *index)
3104 DWORD ret;
3105 MIB_IFROW row;
3107 TRACE("(%p %p)\n", luid, index);
3109 if (!luid || !index) return ERROR_INVALID_PARAMETER;
3111 row.dwIndex = luid->Info.NetLuidIndex;
3112 if ((ret = GetIfEntry( &row ))) return ret;
3114 *index = luid->Info.NetLuidIndex;
3115 return NO_ERROR;
3118 /******************************************************************
3119 * ConvertInterfaceLuidToNameA (IPHLPAPI.@)
3121 DWORD WINAPI ConvertInterfaceLuidToNameA(const NET_LUID *luid, char *name, SIZE_T len)
3123 DWORD ret;
3124 MIB_IFROW row;
3126 TRACE("(%p %p %u)\n", luid, name, (DWORD)len);
3128 if (!luid) return ERROR_INVALID_PARAMETER;
3130 row.dwIndex = luid->Info.NetLuidIndex;
3131 if ((ret = GetIfEntry( &row ))) return ret;
3133 if (!name || len < WideCharToMultiByte( CP_UNIXCP, 0, row.wszName, -1, NULL, 0, NULL, NULL ))
3134 return ERROR_NOT_ENOUGH_MEMORY;
3136 WideCharToMultiByte( CP_UNIXCP, 0, row.wszName, -1, name, len, NULL, NULL );
3137 return NO_ERROR;
3140 /******************************************************************
3141 * ConvertInterfaceLuidToNameW (IPHLPAPI.@)
3143 DWORD WINAPI ConvertInterfaceLuidToNameW(const NET_LUID *luid, WCHAR *name, SIZE_T len)
3145 DWORD ret;
3146 MIB_IFROW row;
3148 TRACE("(%p %p %u)\n", luid, name, (DWORD)len);
3150 if (!luid || !name) return ERROR_INVALID_PARAMETER;
3152 row.dwIndex = luid->Info.NetLuidIndex;
3153 if ((ret = GetIfEntry( &row ))) return ret;
3155 if (len < strlenW( row.wszName ) + 1) return ERROR_NOT_ENOUGH_MEMORY;
3156 strcpyW( name, row.wszName );
3157 return NO_ERROR;
3160 /******************************************************************
3161 * ConvertInterfaceNameToLuidA (IPHLPAPI.@)
3163 DWORD WINAPI ConvertInterfaceNameToLuidA(const char *name, NET_LUID *luid)
3165 DWORD ret;
3166 IF_INDEX index;
3167 MIB_IFROW row;
3169 TRACE("(%s %p)\n", debugstr_a(name), luid);
3171 if ((ret = getInterfaceIndexByName( name, &index ))) return ERROR_INVALID_NAME;
3172 if (!luid) return ERROR_INVALID_PARAMETER;
3174 row.dwIndex = index;
3175 if ((ret = GetIfEntry( &row ))) return ret;
3177 luid->Info.Reserved = 0;
3178 luid->Info.NetLuidIndex = index;
3179 luid->Info.IfType = row.dwType;
3180 return NO_ERROR;
3183 /******************************************************************
3184 * ConvertInterfaceNameToLuidW (IPHLPAPI.@)
3186 DWORD WINAPI ConvertInterfaceNameToLuidW(const WCHAR *name, NET_LUID *luid)
3188 DWORD ret;
3189 IF_INDEX index;
3190 MIB_IFROW row;
3191 char nameA[IF_MAX_STRING_SIZE + 1];
3193 TRACE("(%s %p)\n", debugstr_w(name), luid);
3195 if (!luid) return ERROR_INVALID_PARAMETER;
3196 memset( luid, 0, sizeof(*luid) );
3198 if (!WideCharToMultiByte( CP_UNIXCP, 0, name, -1, nameA, sizeof(nameA), NULL, NULL ))
3199 return ERROR_INVALID_NAME;
3201 if ((ret = getInterfaceIndexByName( nameA, &index ))) return ret;
3203 row.dwIndex = index;
3204 if ((ret = GetIfEntry( &row ))) return ret;
3206 luid->Info.Reserved = 0;
3207 luid->Info.NetLuidIndex = index;
3208 luid->Info.IfType = row.dwType;
3209 return NO_ERROR;
3212 /******************************************************************
3213 * if_nametoindex (IPHLPAPI.@)
3215 IF_INDEX WINAPI IPHLP_if_nametoindex(const char *name)
3217 IF_INDEX idx;
3219 TRACE("(%s)\n", name);
3220 if (getInterfaceIndexByName(name, &idx) == NO_ERROR)
3221 return idx;
3223 return 0;