/*
    Posadis code snippet collection - http://www.posadis.org/
    Get the list of DNS servers used by the operating system
    Copyright (C) 2004  Meilof Veeningen <meilof@users.sourceforge.net>
    $Id $
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

/*
    getdnsservers.cpp - Get the list of DNS servers used by the OS

    For different OS'ses, different methods are nessecary to find the list of
    DNS servers used. This snippet has the following implementations:

      o Unix: use libresolv
      o Windows: use the IP helper API (this returns an error message under
        Windows 95, but it should work fine under Windows 98 and later)

    The Windows edition of this code borrows heavily from The Code Project:
    http://www.codeproject.com/internet/netcfg.asp.
*/

#include <poslib/poslib.h>

#ifdef _WIN32

/* Win32 implementation: use ip helper */
#include <windows.h>
#include <tchar.h>
#include <iphlpapi.h>
#include <ipifcons.h>


#define ALLOCATE_FROM_PROCESS_HEAP( bytes )		::HeapAlloc( ::GetProcessHeap(), HEAP_ZERO_MEMORY, bytes )
#define DEALLOCATE_FROM_PROCESS_HEAP( ptr )		if( ptr ) ::HeapFree( ::GetProcessHeap(), 0, ptr )
#define REALLOC_FROM_PROCESS_HEAP( ptr, bytes )	::HeapReAlloc( ::GetProcessHeap(), HEAP_ZERO_MEMORY, ptr, bytes )

stl_slist(_addr) get_os_dns_servers() {
  stl_slist(_addr) servers;
  _addr server;

  DWORD WINAPI (*myGetAdaptersInfo)(PIP_ADAPTER_INFO,PULONG);
  DWORD WINAPI (*myGetPerAdapterInfo)(ULONG,PIP_PER_ADAPTER_INFO, PULONG);

  // load iphlpapi.dll functions
  UINT prev = SetErrorMode(SEM_NOOPENFILEERRORBOX);
  HMODULE mod = LoadLibrary("iphlpapi.dll");
  SetErrorMode(prev);
  if (!mod) throw PException("Could not get DNS servers: iphlpapi.dll not available");
  myGetAdaptersInfo =   (DWORD WINAPI (*)(PIP_ADAPTER_INFO,PULONG))GetProcAddress(mod, "GetAdaptersInfo");
  myGetPerAdapterInfo = (DWORD WINAPI (*)(ULONG,PIP_PER_ADAPTER_INFO, PULONG))GetProcAddress(mod, "GetPerAdapterInfo");
  if (myGetAdaptersInfo == NULL || myGetPerAdapterInfo == NULL)
    throw PException("Could not get DNS servers: wrong iphlpapi DLL");

  try {
    IP_ADAPTER_INFO *pAdptInfo = NULL, *pNextAd = NULL;
    ULONG ulLen = 0;
    int erradapt = 0;

    erradapt = myGetAdaptersInfo( pAdptInfo, &ulLen );
    if( erradapt == ERROR_BUFFER_OVERFLOW ) {
      pAdptInfo = ( IP_ADAPTER_INFO* )ALLOCATE_FROM_PROCESS_HEAP( ulLen );
      erradapt = myGetAdaptersInfo( pAdptInfo, &ulLen );
    }

    if( erradapt != ERROR_SUCCESS ) throw PException("Could not get DNS servers: calling GetAdaptersInfo failed");

    pNextAd = pAdptInfo;

    while( pNextAd ) {
      IP_ADDR_STRING* pNext = NULL;
      IP_PER_ADAPTER_INFO* pPerAdapt = NULL;

      erradapt = myGetPerAdapterInfo( pNextAd->Index, pPerAdapt, &ulLen );
      if ( erradapt == ERROR_BUFFER_OVERFLOW ) {
        pPerAdapt = ( IP_PER_ADAPTER_INFO* ) ALLOCATE_FROM_PROCESS_HEAP( ulLen );
        erradapt = myGetPerAdapterInfo( pNextAd->Index, pPerAdapt, &ulLen );
      }

      if( erradapt == ERROR_SUCCESS ) {
        pNext = &( pPerAdapt->DnsServerList );
        while( pNext ) {
          txt_to_addr(&server, pNext->IpAddress.String);
          servers.push_front(server);
          pNext = pNext->Next;
        }
      }

      DEALLOCATE_FROM_PROCESS_HEAP( pPerAdapt );

      pNextAd = pNextAd->Next;
    }

    DEALLOCATE_FROM_PROCESS_HEAP( pAdptInfo );

    if (servers.empty()) throw PException("No DNS servers defined");
    servers.reverse();
  } catch (PException p) {
    FreeLibrary(mod);
    throw p;
  }

  return servers;
}

#else
#if defined(HAVE_RESOLV_H)

/* Unix implementation: use libresolv */

#if defined(HAVE_NAMESER_H)
#include <nameser.h>
#endif

#include <resolv.h>

stl_slist(_addr) get_os_dns_servers() {
  stl_slist(_addr) servers;
  _addr tmp;
  int t;

  res_init();
  for (t = 0; t < _res.nscount; t++) {
    memcpy(&tmp, &_res.nsaddr_list[t], sizeof(sockaddr_in));
    servers.push_front(tmp);
  }

  if (t == 0) throw PException("No DNS servers defined");
  servers.reverse();

  return servers;
}

#else

/* default implementation */

stl_slist(_addr) get_os_dns_servers() {
  throw PException("Listing used DNS servers is not supported on your OS");
}

#endif
#endif

stl_string addrs_to_string(stl_slist(_addr)& servers) {
  stl_string ret = "";
  stl_slist(_addr)::iterator it = servers.begin();

  while (it != servers.end()) {
    ret += addr_to_string(&*it).c_str();
    ret += ",";
    it++;
  }

  if (ret.size()) ret = ret.substr(0, ret.size() - 1);
  return ret;
}


syntax highlighted by Code2HTML, v. 0.9.1