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.
Related
I'm trying use the python socket module to connect to an ngrok server. If I put the ngrok into my browser it connects properly so the problem is somewhere with my client code. Here is the server code:
#server.py
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)
if __name__ == "__main__":
HOST, PORT = "192.168.86.43", 8080
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
And here is the client:
#client.py
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("http://urlhere.ngrok.io", 8080))
sock.sendall(bytes("Hello" + "\n", "utf-8"))
Thanks!
In general you should be able to connect to any globally available address or DNS name, ensuring there is no network restrictions on the way. However you have to listen on the address that is locally available for global routing if you are communicating across the Internet.
As for particular code, there are 2 issues:
Socket should be connected to an address or DNS name. The protocol is defined with the socket type. In your case
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect(("localhost", 8080))
sock.sendall(bytes("Hello" + "\n", "utf-8"))
You're binding in the server to some speciffic not related address. To run your code you should bind to either localhost or to "any available" address "0.0.0.0":
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)
if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 8080
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
I have a basic python server up using http.server in Python 3, not simplehttpserver
import http.server
import socketserver
PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
And I need to get the clients IP address when they send a request, can anyone help me.
Thank you in advance.
You can port that duplicate answer to Python 3 by fixing up the imports:
import http.server
import socketserver
class MyHandler(http.server.SimpleHTTPRequestHandler):
def handle_one_request(self):
print(self.client_address[0])
return super().handle_one_request()
httpd = socketserver.TCPServer(("", 8080), MyHandler)
while True:
httpd.handle_request()
I have a simple script to run a python server
I would like to run a code when a request is sent to the server.
I'm wondering if I should use a handler or something similar.
Here is my script"
#!/usr/bin/python
import BaseHTTPServer
import CGIHTTPServer
PORT = 8888
server_address = ("", PORT)
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
handler.cgi_directories = ["/"]
print "Serveur actif sur le port :", PORT
httpd = server(server_address, handler)
httpd.serve_forever()
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
I'm trying to create the ability for a client to enter the IP address/port of a server and connect to it. In order to do this, I need the server's public IP address/port. Is there a good way to do this? What I've tried so far is...
ip_address = urllib.request.urlopen(<my web server>).read()
with the web server just containing the php script:
<?php echo $_SERVER["REMOTE_ADDR"]?>
And just storing the port from the
s.bind(('', port))
Connecting to this ip address and port times out. Is there a better way to do this?
EDIT:
OK so basically I'm trying to establish a connection over the internet, without knowing exactly what my router is going to be doing. I can use a webserver with any code if necessary, as I have access to permanent webspace. This is what I have right now.
Server:
import urllib.request
import threading
import socket
socket_list = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 0))
s.listen(10)
def listener(socket):
while(1):
data = socket.recv(1024)
print (data)
def accepter():
while(1):
socket, addr = s.accept()
socket_list.append(socket)
threading.Thread(target = listener, args = (socket,)).start()
ip_address = (urllib.request.urlopen("<MY WEB SERVER HERE>").read()).decode('utf-8')
print (ip_address)
print (s.getsockname()[1])
threading.Thread(target = accepter, args = ()).start()
Client:
import socket
print ("Enter IP Address")
ip_address = input()
print ("Enter Port")
port = int(input())
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s2.connect((ip_address, port))s2.send("Connected!")
s2.close()
When I run the client I'm entering the IP address and port that are outputted by the server. Needless to say, this doesn't work.
I thought this was a good question you can do it like this if you didn't want to have your server set up like you have:
""" Easy IP Getter """
import json
import urllib2
info = json.loads(urllib2.urlopen("http://jsonip.com").read())
ip = info["ip"]
print ip
It depends on an outside service however which isn't the best, if they stop working you stop working.