Opening the localhost web from another device using Python - python

I'm working on a python file that sends the response to the localhost website opened by the browser. This web can successfully open by the same device which hosts it, but when failed to be opened by the other device under the same LAN. Why does that happen?
I use http.server in Python3 to host the local server. I'm using these codes:
from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
hostPort = 9000
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
path = self.path
print(path)
referer = self.headers.get('Referer')
print("The referer is", referer)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# str is the html code I used
self.wfile.write(bytes(str, "utf-8"))
myServer = HTTPServer((hostName, hostPort), MyServer)
print("Server Starts - %s:%s" % (hostName, hostPort))
try:
myServer.serve_forever()
except KeyboardInterrupt:
pass
myServer.server_close()
print("Server Stops - %s:%s" % (hostName, hostPort))
I am able to open the web by using localhost and 127.0.0.1, but just not the ip address.
Can anyone help me, please? Thank you

Use your machine's IP address instead of localhost(Loopback) as the host. If your machine's IP is 192.168.x.x then the server will run at: 192.168.x.x:9000.

Related

How to connect a "client" socket on any network in the world to my "socket server"

I made a socket to see how it works.
Basically my intention for testing was to run commands in client computer cmd
First I made the server to receive a connection from my other script client
import socket
HOST = '192.168.100.xx' #my computer ipv4
PORT = 50000
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((HOST,PORT))
server.listen(5)
print('Server waiting connection...')
conn,addr = server.accept()
print('Connection established!')
print('Connected in addr: {}\n'.format(addr))
while True:
cmd = str(input('command>'))
conn.send(str.encode(cmd))
response = str(conn.recv(1024),"utf-8")
print(response)
if cmd == 'quit':
break
server.close()
Then I made the client:
import socket
import subprocess
import os
HOST = '192.168.100.xx' #ipv4 from my computer (server)
PORT = 50000
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((HOST,PORT))
print('Connecting to the server {}'.format(HOST))
while True:
command = client.recv(1024).decode()
print('Server command>'+command)
cmd = subprocess.Popen(args=command,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output = (cmd.stdout.read() + cmd.stderr.read()).decode("utf-8", errors="ignore")
client.send(str.encode(str(output)+ str(os.getcwd()) +'$'))
Here's how I get my IPv4 address:
Initially when I tested it on a machine on my network this worked fine, but when I sent the client to a friend far away to run it, it didn't work.
I would like to know what I do to be able to use my socket server to connect with socket client in any corner of the world.
You are using a local ip which allows people connected only to your router connect.
So you need to use your public ip address. (Click Here to check your IP)
Open a port in your router. for example: 1234.
Dont know how? See this video.
Want to learn about it? See this video.
Once you do that, change the port in your code to the port you opened on the router page.
and then change the ip in the client code to your public ip.
Now your friend should be able to connect to your server.
(also you need to have static ip and not dynamic ip)

HTTPS connection Python still loading the content until it's KeyboardInterrupted

Can anyone tell me what's the solution for this?
When I run it and load it from the browser... It's only loading and never displaying the "Hello Word!" text.
But the text will appear in the browser after I shutdown the server by triggering the KeyboardInterrupt.
PS: SSL is enabled in python 2.6 interpreter on Linux. Also, it's not working in Windows 7.
Here's the code:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import ssl
import sys
PORT_NUMBER = int(sys.argv[1])
#This class will handles any incoming request from the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
print(self.requestline)
#print(self.rfile.read(content_length))
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write("Hello World !".encode())
return
try:
#Create a web server and define the handler to manage the
#incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
server.socket = ssl.wrap_socket(server.socket, certfile='cert.pem',keyfile='key.pem', server_side=True)
print 'Started httpserver on port ' , PORT_NUMBER
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
in order to run this in Python 2.x, command: python this_code.py [port]
Example:
python this_code.py 8080
Then navigate to the browser with the address: https://localhost:8080/
If I remove this line, it'll work but it's just running under HTTP protocol and not in HTTPS (which I'm intended to run in):
server.socket = ssl.wrap_socket(server.socket, certfile='cert.pem',keyfile='key.pem', server_side=True)

How do I wirelessly connect to a computer using python

I am wondering if there is any way to wirelessly connect to a computer/server using python's socket library. The dir(socket) brought up a lot of stuff and I wanted help sorting it out.
but one question. Is the socket server specific to python, or can
another language host and python connect or vise-versa?
As long as you are using sockets - you can connect to any socket-based server (made with any language). And vice-versa: any socket-based client will be able to connect to your server. Moreover it's cross-platform: socket-based client from any OS can connect to any socket-based server (from any OS).
It is unclear of what you mean by "Connect to a computer" so I gave you a TCP socket server and client.
Create a socket server on the computer you wish to "connect to" with:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
Now create the client:
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
(SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
sock.sendall(data + "\n")
received = sock.recv(1024)
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
You run the server and then the client and the server should receive the client's connection and send it whatever you have as the data variable on the server. Source: https://docs.python.org/2/library/socketserver.html

Build a server with BaseHTTPServer for public network?

Trying to build a simple server:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("It works!")
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
try:
server = HTTPServer(('localhost', 8080), MyHandler)
print 'started httpserver...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
Well, it works on 127.0.0.1:8080, but now I want to access it through public network like my ip:8080, what should I do?
Edit: HTTPServer(('0.0.0.0', 8080), MyHandler) does not work for me, any idea why?
I'm on win 7 ultimate 64bit, python 2.7.3
Specify '0.0.0.0' or '' (empty string) to make the server accept connections from anywhere.
server = HTTPServer(('0.0.0.0', 8080), MyHandler)
The address ('0.0.0.0', 8080) is passed to socket.bind. 0.0.0.0 is used to bind to any local network interfaces.

Python Server on different IP address

So I have a web server that I can run using python, but I have a question. Can I change the IP address where the server runs the only one I can get to work is 127.0.0.1 which is the localhost address? I have already tried with no luck I want to use a unused one on my network.
Here's the code:
import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
HandlerClass = SimpleHTTPRequestHandler
ServerClass = BaseHTTPServer.HTTPServer
Protocol = "HTTP/1.0"
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 8000
server_address = ('127.0.0.1', port)
HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
print "Running server on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
You can only use addresses that are bound to a network interface on the computer. You cannot use random addresses picked out of thin air.

Categories