我对搜索本地网络的更快/不同方式有疑问。
这是我为搜索本地网络,代码工作所做的一些代码,但我不确定这是一种很好的方法来加快搜索速度。我在MSDN上读到我应该使用线程来进行此beacuze getnameinfo不支持超时控制。
问题是,这是加强搜索的好方法还是有更好的方法?
任何提示都将不胜感激!!
谢谢:))
// link with ws2_32.lib
#pragma comment(lib, "Ws2_32.lib")
void check_ip_address(char* adradr)
{
// Declare and initialize variables
WSADATA wsaData = {0};
int iResult = 0;
DWORD dwRetval;
struct sockaddr_in saGNI;
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;
std::string str;
std::stringstream ss;
std::ofstream log_file;
std::ostream_iterator<std::string> os(log_file, "\n");
std::vector<std::string> vec;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
std::cout<< "WSAStartup failed: %d\n" << iResult;
}
// Set up sockaddr_in structure which is passed
// to the getnameinfo function
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = inet_addr(adradr);
saGNI.sin_port = htons(port);
// Call getnameinfo
dwRetval = getnameinfo((struct sockaddr *) &saGNI,
sizeof (struct sockaddr),
hostname,
NI_MAXHOST, servInfo, NI_MAXSERV, NI_NUMERICSERV);
if (dwRetval != 0) {
std::cout<< "getnameinfo failed with error # %ld\n" << WSAGetLastError();
}
else {
std::cout<< adradr << " --> getnameinfo returned hostname = " << hostname << std::endl;
}
log_file.open("log.txt", std::ios::app);
ss << adradr << " --> getnameinfo returned hostname = " << hostname;
str = ss.str();
vec.push_back(str);
copy(vec.begin(), vec.end(), os);
log_file.close();
}
int main()
{
std::ofstream log_file;
char* charr_address = "192.168.";
log_file.open("log.txt");
log_file.close();
for(int i = 1; i < 6; i++)
{
for(int j = 0; j < 255; ++j)
{
//function that concat/deconcat address(nothing special)
charr_address = concat_deconcat_address(charr_address, i, j);
std::thread t1(check_ip_address, charr_address);
t1.detach();
}
}
std::this_thread::sleep_for (std::chrono::seconds(15));
return 0;
}