When hosting a simple http.server.BaseHTTPRequestHandler server from Python, I would like to get the ip address of anyone accessing my server. I looked around, and I found solutions in Java and C, but nothing in Python. When I tried to convert the solutions in either language, they would not work. The GetIp from Java was not a part of the BaseHTTPRequestHandler class, nor was the UserHostName from C. I also am not serving from Flask, bottle, or any other serving platform, so I cannot use any of their methods. How would I do this?
- Please don't add "solved" to your title or question. Instead, mark an answer correct by clicking on the checkmark. You can also add your own answer and accept it if none of the ones you received solved your problem.Chris– Chris2020-04-27 23:34:57 +00:00Commented Apr 27, 2020 at 23:34
- And please don't artificially "tag" your titles. Use the real tags that Stack Overflow provides.Chris– Chris2020-04-27 23:35:30 +00:00Commented Apr 27, 2020 at 23:35
- In this: stackoverflow.com/help/how-to-ask, it said to be as descriptive as possible in your titles, so I tried to let the users know they were getting into a question about Python, because this is a topic that could be problematic across multiple languages. But yes, I will admit that I was wrong with the [solved] in the answer.User 12692182– User 126921822020-04-27 23:50:22 +00:00Commented Apr 27, 2020 at 23:50
- Again, that's what actual tags are for. You correctly included the python tag; don't make up some tagging format to cram into your title.Chris– Chris2020-04-27 23:52:06 +00:00Commented Apr 27, 2020 at 23:52
Add a comment |
2 Answers
There is subclass, request that is part of the BaseHTTPRequestHandler class, and inside it is are functions that will tell you ip addresses of your server, and the machines accessing it. Add this to your do_GET function: self.request.getpeername()
This will return a tuple of the form:
(their ipv4 address, their port) Comments
It is directly accessible as an instance variable of BaseHTTPRequestHandler like request_handler.client_address (suppose request_handler inherits from BaseHTTPRequestHandler), which will return a tuple of the form (host, port) referring to the client’s address.