Python – Accessing device via global IP instead of port forwarding on router

flaskport-forwardingpythonremote-access

I have a python script hosted on a remote server. Lets say the URL given by the hosting site is "myproject.host.com". The following is a part of the script:

import json
import socket
from flask import Flask
from flask import request
from flask import make_response
app=Flask(__name__)

# domain given by noip.com, forwarded port
ip = ('abc.noip.org', 9050)

# used to find device's global IP address, and modify the variable ip accordingly
@app.route('/findMyIP',methods=['GET'])
def findMyIP():
    global ip
    mip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
    print(mip)
    ip = (mip,9050)
    return mip

@app.route('/webhook',methods=['GET'])
def webhook(data = 'Test Message'):
    # I am using UDP protocol
    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    sock.sendto(data.encode(),ip)
    sock.close()
    return 'data sent'

I have port forwarded my router to access a device on the local network via the internet.

Lets say that the domain given by noip.com is abc.noip.org, and the forwarded port is 9050.

With this setup, I am able to access my device without any issue.

My aim is to access the device using its global IP address, without having to set up port forwarding every time I use a different router, or when I use a hotspot.

I tried doing this:

-> From the device, I connect to "myproject.host.com/findMyIP". This usually shows the device IP to be of the form 10.xx.xx.xxx.

-> I try communicating to the device using the IP address obtained from the above step.

But I am not able to get it to work. What am I missing here?

Best Answer

The IP address is actually the address of your router's WAN network interface, because of this, the router has no idea that a new incoming connection is actually meant for your device on the router's LAN.

Ultimately, the router knows that the packet is destined for the device if either there exists a rule (such as a port forwarding or DMZ), or if it has seen the device send a relevant packet the other way first.

Many different methods for connecting to a server behind a SNAT exist, however one of my favourite is pwnat by Samy Kamkar since this does not require a third-party server, however, this will require that the client also connects using pwnat.

Alternatively, if you have a publicly accessible server, you can set up a SSH reverse tunnel. This may be preferable if you wish to share the service with others.

Ultimately, the options above are less preferable to port forwarding and only should be considered where you have no control over the router.

Related Topic