Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Port forwarding in python to allow socket connections

I start a server using sockets and want to allow clients to connect to it.

self.sock.bind(('0.0.0.0',0)) # 0.0.0.0 will allow all connections and port 0 -> os chooses a open port.
stroke_port=self.sock.getsockname()[1]
self.sock.listen(75)
self.open_port_popup(stroke_port)

Now, for other clients to connect I have port forward it manually and it works fine. enter image description here

I want to do this in automated fashion. -> I try upnp.

import miniupnpc

def open_port(port_no):
    '''this function opens a port using upnp'''
    upnp = miniupnpc.UPnP()

    upnp.discoverdelay = 10
    upnp.discover()

    upnp.selectigd()

    # addportmapping(external-port, protocol, internal-host, internal-port, description, remote-host)
    result=upnp.addportmapping(port_no, 'TCP', upnp.lanaddr, port_no, 'testing', '')
    return result

It opens a port shown in the image below. But the port-forwarding list shown in the first image is empty. It doesn't work and clients can't connect. How can I fix this? What am I missing? enter image description here

like image 315
Abhishek Bhatia Avatar asked Mar 21 '16 04:03

Abhishek Bhatia


2 Answers

I think you made a mistake using upnp.lanaddr as internal-host address. upnp.lanaddr is the address of the upnp device which is your router, you want to use the local address of your server.

If needed take a look at Finding local IP addresses using Python's stdlib if you want to get your server local IP dynamically.

like image 156
MajorTom Avatar answered Nov 13 '22 09:11

MajorTom


I think that we are missing lot of related info to know what's the main problem here. I see so many people guessing.

By the way, just editing that line

result=upnp.addportmapping(port_no, 'TCP', upnp.lanaddr, port_no, 'testing', '') to

result=upnp.addportmapping('7777', 'TCP', '192.168.1.8', '7777', 'testing', '') would tell you if it works at all. Doing port testing from localhost it's dummy, you're not under the router at all.

Also, remember to use Try/Except blocks to tell you what's wrong on your code.

try:
    print "1" + 1
except Exception as e:
    print str(e) 

Another way, not fashioned is to use html/web automation, even cURL to make those requests instead using uPnp, this way you don't really need to handle it.

like image 31
m3nda Avatar answered Nov 13 '22 09:11

m3nda