11

I am making a Python application that requires the user to have a port forwarded to his computer in order to communicate with a server or another user. The current implementation works quite great, yet the only thing is that the person who's running the file must forward the port to the local IP manually. I want to automate this. He picks a port, script checks if it can be forwarded, then it forwards it. If it can't, it handles the error respectively.

I've looked into some libraries that claim they can do this in pure Python (since I will need to compile to .exe's [...] after finishing) but didn't manage to find something useful. If you could provide me with a code sample on how to attempt to forward a port and handle success/fail respectively, that would be great.

Thanks in advance for your time.

P.S.:It's Python 2.7.X that I am targeting

DaKnOb
  • 577
  • 4
  • 17
  • P.S.: The app will be developed on a Mac and later tested on a Windows machine. If it works, it will be compiled and deployed to all platforms. – DaKnOb Jan 23 '13 at 19:40
  • I was looking into the same thing, unfortunately I found only [Brisa](http://stackoverflow.com/q/4742001/897968) and [MiniUPNP](http://stackoverflow.com/a/10440556/897968) so far... there surely must be a more current/compact/pure Python implementation? Anyone? – FriendFX May 07 '13 at 04:54
  • Looking for cross-platform solution here. – Abhishek Bhatia Mar 21 '16 at 01:55
  • @AbhishekBhatia I will be trying the one answer provided and in general work on this for a few minutes. Since this was almost 3 years ago I do not remember exactly what I did. I probably abandoned the port forwarding idea. Let me know if you come up with something too. – DaKnOb Mar 21 '16 at 13:19
  • @DaKnOb Hi, thanks. I tried this https://stackoverflow.com/questions/36123075/port-forwarding-in-python-to-allow-socket-connections . But it doesn't seem to work though. Let me know if possible. – Abhishek Bhatia Mar 22 '16 at 03:31

1 Answers1

1

Looks like there are a few options:

There is a nice example of the python bindings for GNUPnP being used to open ports on a router here. In that example the lease time is set to 0, which is unlimited. See here for the definition of add_port.

A simple example might be:

#! /usr/bin/python
import gupnp.igd
import glib
from sys import stderr

my_ip = YOUR_IP

igd = gupnp.igd.Simple()
igd.external_ip = None

main = glib.MainLoop()

def mep(igd, proto, eip, erip, port, localip, lport, msg):
    if port == 80:
        igd.external_ip = eip
        main.quit()

def emp(igd, err, proto, ep, lip, lp, msg):
    print >> stderr, "ERR"
    print >> stderr, err, proto, ep, lip, lp, msg
    main.quit()

igd.connect("mapped-external-port", mep)
igd.connect("error-mapping-port", emp)

#igd.add_port("PROTO", EXTERNAL_PORT, INTERNAL_IP, INTERNAL_PORT, LEASE_DURATION_IN_SECONDS, "NAME")
igd.add_port("TCP", 80, my_ip, 8080, 86400, "web")

main.run()
KernelSanders
  • 387
  • 3
  • 10