Instantly share code, notes, and snippets.

Embed
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);
free(reply);
const char *resVal = GetValueFromNameValueList(&pdata, "errorCode");
ClearNameValueList(&pdata);
retcode = atoi(resVal?resVal:"0");
FreeUPNPUrls(&urls);
freeUPNPDevlist(devlist);
printf("\n\n");
return retcode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment