Skip to content

Instantly share code, notes, and snippets.

@yne yne/upnp_port.c
Created Mar 12, 2017

What would you like to do?
UPNP port forwarding managment
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <ctype.h>
#include "miniwget.h"
#include "miniupnpc.h"
#include "upnpcommands.h"
#include "upnperrors.h"
#include "miniupnpcstrings.h"
int main(int argc, char ** argv) {
int error = 0;
struct UPNPDev * devlist = upnpDiscover(2000, NULL, NULL, UPNP_LOCAL_PORT_ANY, 0, 2, &error);
if( devlist == NULL){
fprintf(stderr, "No IGD UPnP Device found on the network !\n");
return 1;
struct UPNPUrls urls;
struct IGDdatas data;
char lanaddr[64] = "unset"; /* my ip address on the LAN */
int i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if( !i ){
fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n");
return 1;
//printf("IGD(%i):%s, self:%s\n", i, urls.controlURL, lanaddr);
int bufsize;
int retcode = 0;
char * reply = NULL;
if (argv[1][0]=='a')
reply = upnp_cmd(-1, urls.controlURL, data.first.servicetype, "AddPortMapping", (struct UPNParg []){ {"NewRemoteHost",NULL}, {"NewExternalPort","2345"},{"NewProtocol","UDP"},{"NewInternalPort","1234"},{"NewInternalClient",lanaddr},{"NewEnabled","1"},{"NewPortMappingDescription","Eldorado"},{"NewLeaseDuration","0"},{NULL},}, &bufsize);
if (argv[1][0]=='d')
reply = upnp_cmd(-1, urls.controlURL, data.first.servicetype, "DeletePortMapping", (struct UPNParg []){ {"NewRemoteHost",NULL}, {"NewExternalPort","2345"}, {"NewProtocol","UDP"}, {NULL},}, &bufsize);
if(!reply)return fprintf(stderr,"%c failed\n", argv[1][0]),3;
struct NameValueParserData pdata;
ParseNameValue(reply, bufsize, &pdata);
const char *resVal = GetValueFromNameValueList(&pdata, "errorCode");
retcode = atoi(resVal?resVal:"0");
return retcode;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.