Skip to content

Instantly share code, notes, and snippets.

@edg-l

edg-l/miniupnpc_example.c Secret

Created Jun 24, 2020
Embed
What would you like to do?
#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