Skip to content

Instantly share code, notes, and snippets.

@edg-l
Created June 24, 2020 08:34
Show Gist options
  • Save edg-l/98241d2ef929661f0bb20136ebda16cd to your computer and use it in GitHub Desktop.
Save edg-l/98241d2ef929661f0bb20136ebda16cd to your computer and use it in GitHub Desktop.
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#include <stdio.h>
int main() {
struct UPNPUrls upnp_urls;
struct IGDdatas upnp_data;
struct UPNPDev *upnp_dev = 0;
char aLanAddr[64];
const char *pPort = "8000";
int error = 0;
upnp_dev = upnpDiscover(2000, NULL, NULL, 0, 0, 2, &error);
// Retrieve a valid Internet Gateway Device
int status = UPNP_GetValidIGD(upnp_dev, &upnp_urls, &upnp_data, aLanAddr,
sizeof(aLanAddr));
printf("status=%d, lan_addr=%s\n", status, aLanAddr);
if (status == 1) {
printf("found valid IGD: %s\n", upnp_urls.controlURL);
error =
UPNP_AddPortMapping(upnp_urls.controlURL, upnp_data.first.servicetype,
pPort, // external port
pPort, // internal port
aLanAddr, "My Application Name", "UDP",
0, // remote host
"0" // lease duration, recommended 0 as some NAT
// implementations may not support another value
);
if (error) {
printf("failed to map port\n");
printf("error: %s\n", strupnperror(error));
} else
printf("successfully mapped port\n");
} else {
printf("no valid IGD found\n");
}
// Open a socket bound to the internal port and do your stuff.
// Cleanup
error = UPNP_DeletePortMapping(upnp_urls.controlURL, upnp_data.first.servicetype,
pPort, "UDP", 0);
if(error != 0) {
printf("port map deletion error: %s\n", strupnperror(error));
}
FreeUPNPUrls(&upnp_urls);
freeUPNPDevlist(upnp_dev);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment