Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dagelf/316f21e02b3be0c7ce2141bba5f85d69 to your computer and use it in GitHub Desktop.
Save dagelf/316f21e02b3be0c7ce2141bba5f85d69 to your computer and use it in GitHub Desktop.
Port forwarder using miniupnp library
/* $Id: upnpc.c,v 1.101 2014/01/31 13:18:25 nanard Exp $ */
/* Project : miniupnp
MiniUPnPc
Copyright (c) 2005-2016, Thomas BERNARD
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
* --------------------------------------------------------------------------
* Modified by Shoaib Ahmed (AKA Sufi-Al-Hussaini)
* --------------------------------------------------------------------------
*
* cc -fPIC -O -Wall -W -Wstrict-prototypes -fno-common -DMINIUPNPC_SET_SOCKET_TIMEOUT -DMINIUPNPC_GET_SRC_ADDR -D_BSD_SOURCE -D_POSIX_C_SOURCE=1 -ansi -c -o upnpc-t.o miniupnp_port_forwarder.c
* cc -o miniupnp_port_forwarder upnpc-t.o libminiupnpc.a
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <winsock2.h>
#define snprintf _snprintf
#else
/* for IPPROTO_TCP / IPPROTO_UDP */
#include <netinet/in.h>
#endif
#include "miniwget.h"
#include "miniupnpc.h"
#include "upnpcommands.h"
#include "upnperrors.h"
#define IP_ETH0 "192.168.1.234"
#define INT_PORT "1234"
#define EXT_PORT "1234"
#define PROTOCOL "TCP"
#define DURATION "0"
#define DESCRIPTION "PORT FORWARDER"
/* protofix() checks if protocol is "UDP" or "TCP"
* returns NULL if not */
const char * protofix(const char * proto)
{
static const char proto_tcp[4] = { 'T', 'C', 'P', 0};
static const char proto_udp[4] = { 'U', 'D', 'P', 0};
int i, b;
for(i=0, b=1; i<4; i++)
b = b && ( (proto[i] == proto_tcp[i])
|| (proto[i] == (proto_tcp[i] | 32)) );
if(b)
return proto_tcp;
for(i=0, b=1; i<4; i++)
b = b && ( (proto[i] == proto_udp[i])
|| (proto[i] == (proto_udp[i] | 32)) );
if(b)
return proto_udp;
return 0;
}
/* Test function
* 1 - get connection type
* 2 - get extenal ip address
* 3 - Add port mapping
* 4 - get this port mapping from the IGD */
static void SetRedirectAndTest(struct UPNPUrls * urls,
struct IGDdatas * data,
const char * iaddr,
const char * iport,
const char * eport,
const char * proto,
const char * leaseDuration,
const char * description)
{
char externalIPAddress[40];
char intClient[40];
char intPort[6];
char duration[16];
int r;
if(!iaddr || !iport || !eport || !proto)
{
fprintf(stderr, "Wrong arguments\n");
return;
}
proto = protofix(proto);
if(!proto)
{
fprintf(stderr, "invalid protocol\n");
return;
}
UPNP_GetExternalIPAddress(urls->controlURL,
data->first.servicetype,
externalIPAddress);
if(externalIPAddress[0])
printf("ExternalIPAddress = %s\n", externalIPAddress);
else
printf("GetExternalIPAddress failed.\n");
r = UPNP_AddPortMapping(urls->controlURL, data->first.servicetype,
eport, iport, iaddr, description,
proto, 0, leaseDuration);
if(r!=UPNPCOMMAND_SUCCESS)
printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
eport, iport, iaddr, r, strupnperror(r));
r = UPNP_GetSpecificPortMappingEntry(urls->controlURL,
data->first.servicetype,
eport, proto, NULL/*remoteHost*/,
intClient, intPort, NULL/*desc*/,
NULL/*enabled*/, duration);
if(r!=UPNPCOMMAND_SUCCESS)
printf("GetSpecificPortMappingEntry() failed with code %d (%s)\n",
r, strupnperror(r));
if(intClient[0]) {
printf("external %s:%s %s is redirected to internal %s:%s (duration=%s)\n",
externalIPAddress, eport, proto, intClient, intPort, duration);
}
}
/* CheckIfMapped()
* 1 - get this port mapping from the IGD
* 2 - confirm if it is mapped, and return 1 if mapped*/
static int CheckIfMapped(struct UPNPUrls * urls,
struct IGDdatas * data,
const char * eport,
const char * proto)
{
char intClient[40];
char intPort[6];
char duration[16];
int r;
r = UPNP_GetSpecificPortMappingEntry(urls->controlURL,
data->first.servicetype,
eport, proto, NULL/*remoteHost*/,
intClient, intPort, NULL/*desc*/,
NULL/*enabled*/, duration);
if(r!=UPNPCOMMAND_SUCCESS) {
printf("GetSpecificPortMappingEntry() failed with code %d (%s)\n",
r, strupnperror(r)); /* This may also happen when external port is not mapped. */
return -1;
}
if(intClient[0]) {
if(!strcmp(intClient, IP_ETH0) && !strcmp(intPort, INT_PORT) && !strcmp(eport, EXT_PORT)) {
printf("Port %s is already redirected to internal %s:%s (duration=%s)\n",
eport, intClient, intPort, duration);
return 1;
} else {
printf("Port %s is redirected to internal %s:%s (duration=%s)\n",
eport, intClient, intPort, duration); /* This happens when external port is mapped to a different client/ port/ protocol. */
return 0;
}
} else{
return -1;
}
}
int main(int argc, char ** argv)
{
struct UPNPDev * devlist = 0;
char lanaddr[64]; /* my ip address on the LAN */
int i;
const char * rootdescurl = 0;
const char * multicastif = 0;
const char * minissdpdpath = 0;
int retcode = 0;
int error = 0;
int ipv6 = 0;
printf("Searching for UPNP devices on network....\n");
if( rootdescurl
|| (devlist = upnpDiscover(2000, multicastif, minissdpdpath,
0/*sameport*/, ipv6, &error)))
{
struct UPNPDev * device;
struct UPNPUrls urls;
struct IGDdatas data;
if(devlist)
{
printf("List of UPNP devices found on the network :\n");
for(device = devlist; device; device = device->pNext)
{
printf(" desc: %s\n st: %s\n\n",
device->descURL, device->st);
}
}
else
{
printf("upnpDiscover() error code=%d\n", error);
}
i = 1;
if( (rootdescurl && UPNP_GetIGDFromUrl(rootdescurl, &urls, &data, lanaddr, sizeof(lanaddr)))
|| (i = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr))))
{
switch(i) {
case 1:
printf("Found valid IGD : %s\n", urls.controlURL);
break;
case 2:
printf("Found a (not connected?) IGD : %s\n", urls.controlURL);
printf("Trying to continue anyway\n");
break;
case 3:
printf("UPnP device found. Is it an IGD ? : %s\n", urls.controlURL);
printf("Trying to continue anyway\n");
break;
default:
printf("Found device (igd ?) : %s\n", urls.controlURL);
printf("Trying to continue anyway\n");
}
printf("Local LAN ip address : %s\n", lanaddr);
int mapped;
mapped = CheckIfMapped(&urls, &data, EXT_PORT, PROTOCOL);
if (0 < mapped) { /* Mapped alright */
}
else{ /* Not mapped OR */
if(0 == mapped) /* Mapped wrongly */
UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype,
EXT_PORT, PROTOCOL, 0);
printf("Redirecting....\n");
SetRedirectAndTest(&urls, &data,
IP_ETH0, INT_PORT,
EXT_PORT, PROTOCOL,
DURATION,
DESCRIPTION);
}
FreeUPNPUrls(&urls);
retcode = 0;
}
else
{
fprintf(stderr, "No valid UPNP Internet Gateway Device found.\n");
retcode = 1;
}
freeUPNPDevlist(devlist); devlist = 0;
}
else
{
fprintf(stderr, "No IGD UPnP Device found on the network !\n");
retcode = 1;
}
return retcode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment