Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stupid webserver that returns hostname and primary IP address
#!/usr/bin/python
import BaseHTTPServer
import socket
import fcntl
import struct
address = '0.0.0.0'
port = 12345
interface = 'eth0'
class my_webserver(BaseHTTPServer.BaseHTTPRequestHandler):
'Simple webserving class'
# Process GET requests
def do_GET(self):
global hostname
global my_ip
self.do_return(200, "{: <16} {}\n".format(hostname, my_ip))
# Send response to client
def do_return(self, code, message=""):
global max_requests
if (code == 200):
self.send_response(code)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(message)
# Close the connection so we wont block the client
self.finish()
self.connection.close()
else:
self.send_error(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('ERROR {}\n'.format(message))
# Close the connection so we wont block the client
self.finish()
self.connection.close()
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
hostname = socket.gethostname()
my_ip = get_ip_address(interface)
# Fire up http server and bind to haproxy_healthcheck class
def main():
print("Starting HTTP server on {}:{}".format(address, port))
server = BaseHTTPServer.HTTPServer((address, port), my_webserver)
try:
server.serve_forever()
except KeyboardInterrupt:
print("Closing HTTP server")
server.server_close()
# Run main function
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.