File: dns.c

package info (click to toggle)
haskell-dns 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 380 kB
  • sloc: haskell: 3,298; ansic: 46; makefile: 2
file content (77 lines) | stat: -rw-r--r-- 2,303 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <winsock2.h>
#include <iphlpapi.h>
#include <string.h>
#include <windows.h>
#include <string.h>

#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))

// Fills `dnsAddresses` with the DNS addresses found, up to `bufferLen`.
// Returns NO_ERROR (0x0) in case the operation succeeds, otherwise a non-zero
// error code. See: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
DWORD getWindowsDefDnsServers(char* dnsAddresses, size_t bufferLen) {
    FIXED_INFO *pFixedInfo;
    ULONG ulOutBufLen;
    DWORD dwRetVal;

    if (bufferLen <= 0) return ERROR_NOT_ENOUGH_MEMORY;

    pFixedInfo = (FIXED_INFO *) MALLOC(sizeof (FIXED_INFO));
    if (pFixedInfo == NULL)
      return ERROR_NOT_ENOUGH_MEMORY;
    ulOutBufLen = sizeof (FIXED_INFO);

    // Make an initial call to GetAdaptersInfo to get the necessary size into the
    // ulOutBufLen variable
    if (GetNetworkParams(pFixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
        FREE(pFixedInfo);
        pFixedInfo = (FIXED_INFO *) MALLOC(ulOutBufLen);
        if (pFixedInfo == NULL)
            return ERROR_NOT_ENOUGH_MEMORY;
    }

    dwRetVal = GetNetworkParams(pFixedInfo, &ulOutBufLen);

    if (dwRetVal == NO_ERROR) {
      int offset = 0;
      int spaceAvailable = bufferLen;
      IP_ADDR_STRING* head = &pFixedInfo->DnsServerList;
      int count = 0;

      while (head != NULL) {
        int ipLen = strlen(head->IpAddress.String);
        int copySize = ipLen + 1;

        spaceAvailable -= copySize;
	if (spaceAvailable >= 0) {
	  // Write the separator.
	  // The string is already terminated due to the call to
	  // strcpy_s, which copies the null terminator.
	  if (count != 0) dnsAddresses[offset - 1] = ',';
	  // Copy the IP address, including the null terminator.
	  strcpy_s(dnsAddresses + offset, copySize, head->IpAddress.String);
	  if (spaceAvailable == 0) break;
	} else
	  break;

        offset += copySize;
	count++;
        head = head->Next;
      }

    }

    if (pFixedInfo) FREE(pFixedInfo);
    return dwRetVal;
}

/*

// Test with 'gcc -o dnsServer -Wall -Werror -pedantic -liphlpapi -Iinclude dns.c' on a
// Windows machine.

int main(){
    printf(getWindowsDefDnsServers()->dnsAddresses);
    return 0;
}*/