- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
// Add a UPnP port
bool Win32UPnPAddPort(UINT outside_port, UINT inside_port, bool udp, char *local_ip, wchar_t *description, bool remove_before_add)
{
bool ret = false;
HRESULT hr;
IUPnPNAT *nat = NULL;
wchar_t ip_str[MAX_SIZE];
BSTR bstr_ip, bstr_description, bstr_protocol;
wchar_t *protocol_str = (udp ? L"UDP" : L"TCP");
// Validate arguments
if (outside_port == 0 || outside_port >= 65536 || inside_port == 0 || inside_port >= 65536 ||
IsEmptyStr(local_ip) || UniIsEmptyStr(description))
{
return false;
}
StrToUni(ip_str, sizeof(ip_str), local_ip);
bstr_ip = SysAllocString(ip_str);
bstr_description = SysAllocString(description);
bstr_protocol = SysAllocString(protocol_str);
hr = CoCreateInstance(CLSID_UPnPNAT, NULL, CLSCTX_INPROC_SERVER, IID_IUPnPNAT, (void **)&nat);
if (SUCCEEDED(hr))
{
if (nat != NULL)
{
IStaticPortMappingCollection *collection = NULL;
hr = nat->get_StaticPortMappingCollection(&collection);
if (SUCCEEDED(hr))
{
if (collection != NULL)
{
IStaticPortMapping *mapping = NULL;
if (remove_before_add)
{
hr = collection->Remove((long)outside_port, bstr_protocol);
}
hr = collection->Add((long)outside_port, bstr_protocol, (long)inside_port,
bstr_ip, VARIANT_TRUE, bstr_description, &mapping);
if (SUCCEEDED(hr))
{
ret = true;
if (mapping != NULL)
{
mapping->Release();
}
}
collection->Release();
}
else
{
WHERE;
}
}
else
{
WHERE;
}
nat->Release();
}
else
{
WHERE;
}
}
else
{
WHERE;
}
SysFreeString(bstr_ip);
SysFreeString(bstr_description);
SysFreeString(bstr_protocol);
return ret;
}