#pragma once
#include <new>
#include <vector>
#include <Iphlpapi.h>
#pragma comment(lib, "Iphlpapi.lib")
/////////////////////////////////////////////////////////////////////////////
// CNetParam
class CNetParam
{
public:
CNetParam()
{
m_nBytes = 0;
m_pInfo = NULL;
}
~CNetParam()
{
delete[] (char*) m_pInfo;
}
public:
HRESULT Fetch()
{
HRESULT hr = S_OK;
restart:
ULONG nBytes = m_nBytes;
DWORD dwResult = ::GetNetworkParams(m_pInfo, &nBytes);
switch (dwResult)
{
case NO_ERROR:
return S_OK;
case ERROR_BUFFER_OVERFLOW:
{
hr = Realloc(nBytes);
if (SUCCEEDED(hr))
{
goto restart;
}
return hr;
}
default:
return E_FAIL;
}
}
public:
operator PFIXED_INFO() const
{
return m_pInfo;
}
LPCTSTR HostName() const
{
ATLASSERT(m_pInfo != NULL);
return m_pInfo->HostName;
}
void GetNameServers(std::vector<CString>& serverList, bool bGlobalOnly) const
{
ATLASSERT(m_pInfo != NULL);
for (IP_ADDR_STRING* pIpAddrStr = &m_pInfo->DnsServerList;
pIpAddrStr != NULL; pIpAddrStr = pIpAddrStr->Next)
{
CString strHost;
::memcpy(
strHost.GetBuffer(sizeof(IP_ADDRESS_STRING) + 1),
pIpAddrStr->IpAddress.String,
sizeof(IP_ADDRESS_STRING));
strHost.ReleaseBuffer(sizeof(IP_ADDRESS_STRING));
if (bGlobalOnly)
{
// グローバルアドレス以外を除外する
ULONG addr = htonl(inet_addr(strHost));
if ((addr & 0xFFFF0000) == 0xC0A80000) continue; // 192.168.0.0/16
if ((addr & 0xFFF00000) == 0xAC100000) continue; // 172.16.0.0/12
if ((addr & 0xFF000000) == 0x0A000000) continue; // 10.0.0.0/8
if (addr == 0x7F000001) continue; // 127.0.0.1/32
if (addr == 0xFFFFFFFF) continue; // 255.255.255.255/32
if (addr == 0x00000000) continue; // 0.0.0.0/32
}
serverList.push_back(strHost);
}
}
private:
HRESULT Realloc(ULONG nBytes)
{
try
{
delete[] (char*) m_pInfo;
m_pInfo = (PFIXED_INFO) new char[nBytes];
m_nBytes = nBytes;
}
catch (std::bad_alloc&)
{
return E_OUTOFMEMORY;
}
catch (...)
{
return E_FAIL;
}
return S_OK;
}
private:
ULONG m_nBytes;
PFIXED_INFO m_pInfo;
};