static bool TryHost(const std::string& host)
{
    // WMI waits a long time when the network connection goes down
    // and it cannot resolve DNS, so have Poco do the resolution
    // and then ping using WMI.
    Poco::Net::HostEntry entry;
    try
    {
        entry = Poco::Net::DNS::resolve(host);
    }
    catch (...)
    {
        return false;
    }

    const Poco::Net::HostEntry::AddressList& addresses = entry.addresses();
    for (size_t i = 0; i < addresses.size(); i++)
    {
        const Poco::Net::IPAddress& address = addresses[i];
        if (address.isIPv4Compatible() && TryAddress(address.toString()))
            return true;
    }

    return false;
}
Exemplo n.º 2
0
/**
This function returns the first IP address it can find for a given URL.
@param inputURL: The URL to resolve
@return: The found IP address

@throws: This function can throw exceptions
*/
std::string pylongps::getURLIPAddress(const std::string &inputURL)
{
Poco::Net::HostEntry host;

SOM_TRY
host = Poco::Net::DNS::hostByName(inputURL);
SOM_CATCH("Error, unable to resolve URL\n")

if(host.addresses().size() == 0)
{
throw SOMException("Error resolving URL", UNKNOWN, __FILE__, __LINE__);
}
return host.addresses()[0].toString();
}
Exemplo n.º 3
0
/**
This function attempts to retrieve a Json value from a URL via an http request.  If the request/parsing is successful, the retrieved Json value is stored in the given buffer.  This function is not particularly efficient, so it might be worth considering streamlining the application if that is a concern.
@param inputURL: The URL to retrieve the Json object from
@param inputValueBuffer: The object to store the retrieved value in
@param inputTimeoutDurationInMicroseconds: How long to wait for the value to be return in microseconds
@return: True if successful and false otherwise
*/
bool pylongps::getJsonValueFromURL(const std::string &inputURL, Json::Value &inputValueBuffer, int64_t inputTimeoutDurationInMicroseconds)
{

try
{
Poco::Timestamp startTime;
Poco::Timestamp timeoutTimepoint = startTime+((Poco::Timestamp::TimeDiff) inputTimeoutDurationInMicroseconds);

//Parse URI
Poco::URI url(inputURL);

Poco::Net::HostEntry host;
host = Poco::Net::DNS::hostByName(url.getHost());

if(host.addresses().size() == 0)
{//No IP address for host, so exit silently
return false;
}


Poco::Net::StreamSocket connectionSocket;

connectionSocket.connect(Poco::Net::SocketAddress(host.addresses()[0], 80));

connectionSocket.setReceiveTimeout(timeoutTimepoint-Poco::Timestamp());

Poco::Net::HTTPRequest getRequest("GET", url.getPathAndQuery(), "HTTP/1.1");
getRequest.setHost(url.getHost());

std::stringstream serializedHeader;
getRequest.write(serializedHeader);

connectionSocket.sendBytes(serializedHeader.str().c_str(), serializedHeader.str().size());

std::array<char, 1024> receiveBuffer;
int amountOfDataReceived = 0;
std::string receivedData;
while(Poco::Timestamp() < timeoutTimepoint)
{
amountOfDataReceived = connectionSocket.receiveBytes(receiveBuffer.data(), receiveBuffer.size());

if(amountOfDataReceived == 0)
{
break;
}

receivedData += std::string(receiveBuffer.data(), amountOfDataReceived);

if(receivedData.find("}") != std::string::npos)
{
break;
}
}

if(receivedData.find("{") == std::string::npos)
{
return false;
}

receivedData = receivedData.substr(receivedData.find("{"));

Json::Reader reader;

if(reader.parse(receivedData, inputValueBuffer) != true)
{
return false; //Couldn't parse JSON
}

return true;
}
catch(const std::exception &inputException)
{
return false;
}

}
int Database::ping(std::string domain)
{
	Poco::Net::HostEntry hostEntry = Poco::Net::DNS::hostByName(domain);
	Poco::Net::HostEntry::AddressList addresses = hostEntry.addresses();
	std::string address = addresses[0].toString();

	std::cout << domain << std::endl;
	std::cout << address << std::endl;

	// Declare and initialize variables
	int ms = -1;
	HANDLE hIcmpFile;
	unsigned long ipaddr = INADDR_NONE;
	DWORD dwRetVal = 0;
	DWORD dwError = 0;
	char SendData[] = "Data Buffer";
	LPVOID ReplyBuffer = NULL;
	DWORD ReplySize = 0;

	//std::cout << "test1" << std::endl;

	ipaddr = inet_addr(address.c_str());
	if (ipaddr == INADDR_NONE)
	{
		//std::cout << "test2 - fail" << std::endl;
		return -1;
	}

	//std::cout << "test2" << std::endl;

	hIcmpFile = IcmpCreateFile();
	if (hIcmpFile == INVALID_HANDLE_VALUE) {
		//std::cout << "test3 - fail" << std::endl;
		//printf("\tUnable to open handle.\n");
		//printf("IcmpCreatefile returned error: %ld\n", GetLastError());
		return -1;
	}
	// Allocate space for at a single reply
	ReplySize = sizeof(ICMP_ECHO_REPLY)+sizeof(SendData)+8;
	ReplyBuffer = (VOID *)malloc(ReplySize);
	if (ReplyBuffer == NULL) {
		//std::cout << "test4 - fail" << std::endl;
		//printf("\tUnable to allocate memory for reply buffer\n");
		return -1;
	}
	else {
		dwRetVal = IcmpSendEcho2(hIcmpFile, NULL, NULL, NULL, ipaddr, SendData, sizeof(SendData), NULL, ReplyBuffer, ReplySize, 1000);
		if (dwRetVal != 0)
		{
			PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
			struct in_addr ReplyAddr;
			ReplyAddr.S_un.S_addr = pEchoReply->Address;
			//printf("\tSent icmp message to %s\n", argv[1]);
			if (dwRetVal > 1) {
				//printf("\tReceived %ld icmp message responses\n", dwRetVal);
				//printf("\tInformation from the first response:\n");
			}
			else {
				//printf("\tReceived %ld icmp message response\n", dwRetVal);
				//printf("\tInformation from this response:\n");
			}
			//printf("\t  Received from %s\n", inet_ntoa(ReplyAddr));
			//printf("\t  Status = %ld  ", pEchoReply->Status);
			switch (pEchoReply->Status) {
			case IP_DEST_HOST_UNREACHABLE:
				//printf("(Destination host was unreachable)\n");
				break;
			case IP_DEST_NET_UNREACHABLE:
				//printf("(Destination Network was unreachable)\n");
				break;
			case IP_REQ_TIMED_OUT:
				//printf("(Request timed out)\n");
				break;
			default:
				//printf("\n");
				break;
			}

			//std::cout << "test6" << std::endl;
			//printf("\t  Roundtrip time = %ld milliseconds\n",
			//	pEchoReply->RoundTripTime);
			ms = pEchoReply->RoundTripTime;
		}
		else {
			//printf("Call to IcmpSendEcho2 failed.\n");
			dwError = GetLastError();
			switch (dwError) {
			case IP_BUF_TOO_SMALL:
				printf("\tReplyBufferSize to small\n");
				break;
			case IP_REQ_TIMED_OUT:
				printf("\tRequest timed out\n");
				break;
			default:
				printf("\tExtended error returned: %ld\n", dwError);
				break;
			}
		}
	}

	//Cleanup Memory
	IcmpCloseHandle(hIcmpFile);
	free(ReplyBuffer);

	//Return Ping
	return ms;
}