How do i get the client ip address on a python server - python

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()

Related

python socket not connecting to web server

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()

How can i make a python server open an html file as deafult instead of directory?

here is an example for a simple server:
import http.server
import socketserver
PORT = 80
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
the server itself works and the port is open but it opens the directory the code is in while i need it to open an html file that is in that directory.
How can i make it open the html file i want instead of the directory?
You can extend SimpleHTTPServer.SimpleHTTPRequestHandler and override the do_GET method to replace self.path with your_file.html if / is requested.
import SimpleHTTPServer
import SocketServer
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/your_file.html'
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
Handler = MyRequestHandler
server = SocketServer.TCPServer(('0.0.0.0', 8080), Handler)
server.serve_forever()
More: Documentation

access underlying socket using http.server

I have the following code to run a simple http server
from http.server import SimpleHTTPRequestHandler, HTTPServer
host = "localhost"
port = 8881
server_class = HTTPServer
httpd = server_class((host, port), SimpleHTTPRequestHandler)
print("http server is running {}:{}".format(host, port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
httpd.server_close()
At some point in my code I'd like to access the underlying socket s of the server (which I assume has to acessible somehow) to do something like s.getsockname() for example. Is that possible?
You can access it as self.socket, like so.
httpd.socket.getsockname()
See the source code of the base class SocketServer for more info.
However, for this use case the proper way of doing it is httpd.server_address. In general, you should not try to use the raw socket. Also I would skip the server_class variable and just go HTTPServer((host, port), SimpleHTTPRequestHandler) to keep things simple.

How to add a listener to a python server

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()

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