資源簡介
本代碼為windows端本地DNS服務器簡單實現代碼,可做為相關課程作業參考。本代碼為VS2013編寫,上傳的即為相應的工程,C++代碼實現。
代碼片段和文件信息
/*
*?communication.cpp
*
*??Created?on:?2014年11月1日
*??????Author:?luox?chix?liyicheng
*/
#include?“communication.h“
//using?namespace?std;
Communication::Communication(int?port?char?*?addr)?{
//?TODO?Auto-generated?constructor?stub
this->port?=?port;
memcpy(this->addr?addr?strlen(addr)?+?1);
maxQueueSize?=?100;
vectorMaxNum?=?3;
startAndStop?=?false; //初始化為關閉
debugLevel?=?0;
configFile?=?““;
}
Communication::~Communication()?{
//?TODO?Auto-generated?destructor?stub
}
void?Communication::setCommunication(std::string?debugLevel?/*?=?““?*/?std::string?addr?/*?=?“10.3.9.4“?*/?std::string?configFile?/*?=?“host.txt“?*/)
{
std::stringstream?sstr;
char?ip[16];
//設置默認DNS的地地
ZeroMemory((char?*)&defaultDnsServerAddr?sizeof(defaultDnsServerAddr));
defaultDnsServerAddr.sin_family?=?AF_INET;
defaultDnsServerAddr.sin_port?=?htons(53);
defaultDnsServerAddr.sin_addr.s_addr?=?inet_addr(“10.3.9.4“);
if?(addr?==?““)
{
defaultDnsServerAddr.sin_addr.s_addr?=?inet_addr(“10.3.9.4“);
}
else
{
sstr.clear();
sstr?< sstr?>>?ip;
defaultDnsServerAddr.sin_addr.s_addr?=?inet_addr(ip);
}
//設置配置文件
if?(configFile?==?““)
{
this->configFile?=?“host.txt“;
}
else
{
this->configFile?=?configFile;
}
//設置高度級別
if?(debugLevel?==?““)
this->debugLevel?=?0;
else?if?(debugLevel?==?“-d“)
this->debugLevel?=?1;
else?if?(debugLevel?==?“-dd“)
this->debugLevel?=?2;
else
this->debugLevel?=?3;
}
//初始化
int?Communication::init()
{
//初始化
if?((WSAStartup(MAKEWORD(1?1)?&wsa))?!=?0)
{
return?0;
}
//初始化UDP線程池
threadVectorUDP.reserve(vectorMaxNum);
for?(int?i?=?0;?i? {
threadVectorUDP.push_back(std::thread(std::bind(&Communication::taskProcessUDP?this)));
}
//初始化本地DNS數據
initDNSData();
return?1;
}
void?Communication::initDNSData()
{
std::fstream?host_file(configFile?std::ios::in);
std::string?in;
std::string?domain_name;
std::string?ip;
std::string?ip_temp;
char?ip_char[20];
std::stringstream?sstr;
unsigned?char?temp[4];
int?pos;
unsigned?int?ip_int;
dnsData.clear();
//從配置文件中讀取數據,并存入容器中
while?(getline(host_file?in))
{
if?(in?==?““)
{
continue;
}
pos?=?in.find(‘?‘);
ip_temp?=?in.substr(0?pos);
pos?=?in.rfind(‘?‘);
domain_name?=?in.substr(pos?+?1?in.length()?-?pos);
//轉化成char數組數據
sstr.clear();
sstr?< sstr?>>?ip_char;
//轉化成數字數據
ip_int?=?inet_addr(ip_char);
memcpy(temp?&ip_int?4);
ip?=?““;
for?(int?i?=?0;?i?<=?3;?i?++)
{
ip.append(1?temp[i]);
}
//數據存入容器中
dnsData.insert(std::pair(domain_name?ip));
}
//判斷容器中數據是否為空,若為空,則設本地數據開關為false?否則為true
if?(dnsData.size()?==?0)
{
dnsDataSwitch?=?false;
}
else
{
dnsDataSwitch?=?true;
}
}
//開始監聽
int?Communication::start()
{
startAndStop?=?true; //啟動進程池
init(); //初始化進程池
//啟動UDP監聽
threadListenU
評論
共有 條評論