Ejemplo n.º 1
0
string Mapper_WinUPnP::getExternalIP() {
	// Get the External IP from the last added mapping
	if(!lastPort)
		return Util::emptyString;

	IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection();
	if(!pSPMC)
		return Util::emptyString;

	/// @todo use a BSTR wrapper
	BSTR protocol_ = SysAllocString(Text::toT(protocols[lastProtocol]).c_str());

	// Lets Query our mapping
	IStaticPortMapping* pSPM;
	HRESULT hr = pSPMC->get_Item(lastPort, protocol_, &pSPM);

	SysFreeString(protocol_);

	// Query failed!
	if(FAILED(hr) || !pSPM) {
		pSPMC->Release();
		return Util::emptyString;
	}

	BSTR bstrExternal = 0;
	hr = pSPM->get_ExternalIPAddress(&bstrExternal);
	if(FAILED(hr) || !bstrExternal) {
		pSPM->Release();
		pSPMC->Release();
		return Util::emptyString;
	}

	// convert the result
	string ret = Text::wideToAcp(bstrExternal);

	// no longer needed
	SysFreeString(bstrExternal);

	// no longer needed
	pSPM->Release();
	pSPMC->Release();

	return ret;
}
Ejemplo n.º 2
0
// Returns the current external IP address
_bstr_t UPnP::GetExternalIP() {
	HRESULT hr;

	// Check if we opened the desired port, 'cause we use it for getting the IP
	// This shouldn't be a problem because we only try to get the external IP when
	// we opened the mapping
	// This function is not used somewhere else, hence it is "save" to do it like this
	if(!PortsAreOpen) {
  		return "";
  	}
	BSTR bstrExternal = NULL;
	_bstr_t bstrWrapper;
	CoInitializeEx ( NULL ,COINIT_MULTITHREADED);
	hr = CoCreateInstance (__uuidof(UPnPNAT),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(IUPnPNAT),
		(void**)&pUN);

	if(SUCCEEDED(hr))
	{
			// Get the Collection
			IStaticPortMappingCollection *pIMaps = NULL;
			hr = pUN->get_StaticPortMappingCollection(&pIMaps);

			// Check it
			// We also check against that bug mentioned in OpenPorts()
			if(!SUCCEEDED(hr) || !pIMaps ) {
				 // Only release when OK
				if(pIMaps != NULL) {
					pIMaps->Release();
				}
				pUN->Release();
				pUN=NULL;
				CoUninitialize();
				return "";
			}

			// Lets Query our mapping
			IStaticPortMapping *pISM;
			hr = pIMaps->get_Item(
				PortNumber,
				bstrProtocol,
				&pISM
			);

			// Query failed!
			if(!SUCCEEDED(hr)) {
  				pIMaps->Release();
				pUN->Release();
				pUN=NULL;
				CoUninitialize();
  				return "";
  			}

			// Get the External IP from our mapping
			hr = pISM->get_ExternalIPAddress(&bstrExternal);

			// D'OH. Failed
			if(!SUCCEEDED(hr)) {
  				pIMaps->Release();
				pISM->Release();
				pUN->Release();
				pUN=NULL;
				CoUninitialize();
  				return "";
  			}

			// Check and convert the result
			if(bstrExternal != NULL) {
				bstrWrapper.Assign(bstrExternal);
  			} else {
				bstrWrapper = "";
  			}

			// no longer needed
			SysFreeString(bstrExternal);

			// no longer needed
  			pIMaps->Release();
			pISM->Release();
			pUN->Release();
			pUN=NULL;
			CoUninitialize();
	}

  	return bstrWrapper;
}