资源简介
本代码为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 << addr;
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 < vectorMaxNum; 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 << ip_temp;
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
评论
共有 条评论