I'm using the HTTP server module in Python 3 and I want to make my local HTTP server have a custom url instead of "localhost:8080". Is there any way for me to do this in Python alone without changing default OS settings like the settings in the host file?
When you can setup your router, you must make a port-forwarding. (You usually can setup it on http://192.168.0.1/)
Then you can use that url: "http:// Your Global IP:8080/" for example, when my global IP address is 4.4.0.0, than "http://4.4.0.0:8080/".
When you use the port 80 instead of 8080 (you can setup in port forwarding), it is the professional port of http server, your url will be (with the last example ip): "http://4.4.0.0/"
You can see your global IP address for example on this page: https://whatismyipaddress.com/
or from python code:
gloval_IP = get('https://api.ipify.org').text
Related
This question already has answers here:
Configure Flask dev server to be visible across the network
(17 answers)
Closed 3 months ago.
I am doing experiments with requests trough proxy for web-scraping project.
In order to test requests headers and content i've build a simple flask server like this:
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route("/")
def index():
ret_str = f'<- {request} ->\n' \
f'<----- HEADERS ----->\n' \
f'{request.headers}\n' \
f'<----- DATA ----->\n' \
f'{request.data}\n'
print(ret_str)
return ret_str
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
Which is run perfectly fine if access through localhost by 127.0.0.1:5000 (with app.run()) and through local network by requesting the local address 10.214.14.222:5000 (which is displayed by ipconfig).
But if i try to access it through my 4G connection or through proxy, request fails. According to https://ipchecker.io/, my outside ip is, let's say 216.94.151.186, but requesting my page using 216.94.151.186:5000 gives 'page not found'.
How to access the test server from outside the local network? Can anyone please help?
SOLUTION: Set up port forwarding on router and make computer that run flask server IP-address static on router.
What you'll need to do is make your specified port available on your router. This is done with port forwarding. The location of this tab can switch depending on your router provider but once this is done you can just visit This link which shows your public IP. Then you can just visit: 000.00.000.00:5000 <-- Replace zero's with public IP.
Make sure that port 5000 is opened in your router.
If you have access to linux, you can use nmap to check which ports are open or go to https://portchecker.co/ and check to see if port 5000 is open.
I have a python script that acts as a webhook. A part of it is as follows:
import json
import os
import urllib
import socket
import _thread
from flask import Flask
from flask import request
from flask import make_response
app=Flask(__name__)
ip = ('192.168.1.75', 9050)
#app.route('/webhook',methods=['GET','POST'])
def webhook():
_thread.start_new_thread(sendDataToDevice,(ip))
req = request.get_json(silent=True,force=True)
print("Request:")
print(json.dumps(req,indent=4))
res=makeWebHookResult(req)
res=json.dumps(res,indent=4)
r=make_response(res)
r.headers['Content-Type']='application/json'
return r
if __name__ == '__main__':
app.run(port=8080,host='localhost')
The function of the script is to send some data to a device connected to the local network.
It works flawlessly when I open my web browser and type the following on the url bar:
http://localhost:8080/webhook
I want to host the script on a server, eg. Heroku. How can I access the local device in that case?
Note: I know I can run the script on my local machine and make it visible to the internet using ngrok, but I want to keep it accessible even when my computer is switched off. Also, want a fixed link, and the links given by ngrok change on every run.
I've faced a similar issue before with IoT. Unfortunately there is no simple way to make a device be visible online. Here's a simple solution I've used. It might not be the best, but it works.
DDNS + Port Forwarding + Static IP
If you have access to your local WiFi router, then you can setup something called as DDNS (Dynamic Domain Name System). Your router will then connect to a DDNS service provider like no-ip (www.noip.com) and it will be visible on the internet. You can give a custom URL like susmit-home.noip.com.
However susmit-home.noip.com will now point only to your WiFi router and not your WiFi network. So if you want to access the local device_ip and device_port such as "192.168.1.75", 9050. Then you can setup Port Forwarding on your router for that local IP-Port combination. Usually the setup looks like this:
Local IP: device_ip (e.g. 192.168.1.75)
Local Port: device_port (e.g. 9050)
Outbound Port: any_port (e.g. 9050)
Make sure that your device_ip is a static IP on your WiFi router so that it doesn't change.
Finally in your code you can just replace the line ip = ('192.168.1.75', 9050) with ip = ('susmit-home.noip.com', 9050).
Other solutions:
A slightly more complicated solution is setting up a VPN, such that your local network and your remote server (e.g. Heroku) will all be available to each other as if they were within the same local network.
If your device is a computer or a Raspberry Pi, then you can use SSH Remote Port Forwarding to have access to your local device from the remote server.
I'm trying to run a flask server on my desktop PC that is publicly available on the internet. I've done the following:
Set up a static IP address: 192.168.1.11 (http://i.imgur.com/Z9GEBYV.png)
Forwarded port 33 on my router to my static ip address (http://i.imgur.com/KGNQ2Qk.png)
Setup flask to use my static ip and port: 33
I'm using the following code as a test webserver
from flask import Flask, request, redirect
app = Flask(__name__)
#app.route("/")
def hello_world():
return "Test 123 "
if __name__ == "__main__":
app.run(host="0.0.0.0", port="33")
When I open my browser to: http://192.168.1.11:33/ the page displays properly, I see "Test 123"
My problem comes when trying to connect to my webserver from my public ip address When I open my browser to http://xx.xxx.xxx.xx:30 (my ip address) all I see is "this site can't be reached, xx.xxx.xxx.xx refused to connect"
I've looked up all the stack overflow answers, I've done the following:
Turned off windows firewall
Changed host from "192.168.1.11" to "0.0.0.0"
Tried a different port
screenshot of code running and error shown: http://i.imgur.com/a05GvEs.png
My question is: What do I need to do to make my flask server visible from my public ip address?
Do you have DHCP activated on your router?
If yes do you see your host as 192.168.1.11 in there?
You have to use '0.0.0.0' on host, that tells Flask to listen on all addresses.
Try specifying the port with quotes as app.run(host="0.0.0.0", port="33")
change it to app.run(host= '0.0.0.0', port="33") to run on your machines IP address.
Documented on the Flask site under "Externally Visible Server" on the Quickstart page:
http://flask.pocoo.org/docs/0.10/quickstart/#a-minimal-application
Add port forwarding to port 33 in your router
Port forwarding explained here
http://www.howtogeek.com/66214/how-to-forward-ports-on-your-router/
You must give the public ip address/LAN ip address as an argument to app.run method.
When you don't provide host argument, it works fine with http://localhost:8888/ and http://127.0.0.1:888/, but not to access outside the system where you are running the REST services
Following is the example.
app.run(host="192.168.0.29",debug=True, port=8888)
You must try and use the same ip of the development server. Thus, for instance, if the dev server is running on a PC with the address 192.168.1.11
and port 33, other clients must point at the same address: 192.168.1.11:33.
As far as my small experience, it works with the debugger disabled, but I did not check if this is an essential prerequisite.
good luck
Every webservice should be run from different port address.Single service is running from a single port.
I have an issue with route_url and my setup. On the server I have a paster server which listen on 127.0.0.1 on port 6543 and a nginx server which does reverse proxying from port 80 to port 6543.
I'm also using paste prefix to retrieve the real client IP with this setup in my ini file:
[filter:paste_prefix]
use = egg:PasteDeploy#prefix
[pipeline:main]
pipeline =
paste_prefix
myapp
The server is on a private LAN and I'm trying to connect to the server through a SSH tunnel set up as this:
ssh me#sshgateway -L 8080:nginx_server_ip:80
And I connect to the web page on my client at this url: http://localhost:8080
The main page is displayed correctly but then all links generated with request.route_url are redirecting to localhost/url (without the :8080).
I guess this have something to do either with nginx or paste prefix (or both).
I hope that replacing route_url with route_path will probably solve this problem without fixing the nginx/ini setup issue.
Is there any reason to call route_url instead of route_path, ever ?
route_url is useful in situations like generating a redirect from HTTP to HTTPS, or to a different subdomain. Other than that route_path is probably preferable.
I need client IP address using python. I have tried below code but its not working in server:
from socket import gethostname, gethostbyname
ip = gethostbyname(gethostname())
print ip
On the server, I get '127.0.0.1' every time. Is there any way to find IP address of the client?
You're getting the IP address of your server, not of your server's clients.
You want to look at the request's REMOTE_ADDR, like this:
from bottle import Bottle, request
app = Bottle()
#app.route('/hello')
def hello():
client_ip = request.environ.get('REMOTE_ADDR')
return ['Your IP is: {}\n'.format(client_ip)]
app.run(host='0.0.0.0', port=8080)
EDIT #1: Some folks have observed that, for them, the value of REMOTE_ADDR is always the same IP address (usually 127.0.0.1). This is because they're behind a proxy (or load balancer). In this case, the client's original IP address is typically stored in header HTTP_X_FORWARDED_FOR. The following code will work in either case:
#app.route('/hello')
def hello():
client_ip = request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
return ['Your IP is: {}\n'.format(client_ip)]
EDIT #2: Thanks to #ArtOfWarfare's comment, I learned that REMOTE_ADDR is not required per PEP-333. Couple of observations:
The CGI spec does require REMOTE_ADDR:
The REMOTE_ADDR variable MUST be set to the network address of the client sending the request to the server.
However, PEP-333 does not explicitly require HTTP_REMOTE_ADDR, only going as far as this (emphasis mine):
A server or gateway SHOULD attempt to provide as many other CGI variables as are applicable.
All of the (admittedly few) web frameworks that I'm familiar with set HTTP_REMOTE_ADDR. AFAICT, it's a de facto "standard." But technically, YMMV.
Server might be behind a proxy. Use this for proxy and forward support:
request.environ.get('HTTP_X_FORWARDED_FOR') or request.environ.get('REMOTE_ADDR')
If you're trying to get the external IP, you will need to get it from an external source, i.e whatismyip.com or somewhere that offers an api. If that's what you're looking for, take a look at the Requests module http://docs.python-requests.org/