Last active
June 20, 2019 08:48
-
-
Save wambu-i/047175fca861714563ad39ab46798519 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import logging | |
import os | |
from http.server import HTTPServer, BaseHTTPRequestHandler, SimpleHTTPRequestHandler | |
import socket | |
formatter = '[%(asctime)-15s] %(levelname)s [%(filename)s.%(funcName)s#L%(lineno)d] - %(message)s' | |
logging.basicConfig(level = logging.DEBUG, format = formatter) | |
logger = logging.getLogger('myip') | |
def get_ip_address(ipv6=True): | |
sock = None | |
if ipv6: | |
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) | |
sock.connect(("2001:4860:4860::8888", 80)) | |
else: | |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
sock.connect(("8.8.8.8", 80)) | |
return sock.getsockname()[0] | |
class MyIpServer(SimpleHTTPRequestHandler): | |
def set_headers(self, code): | |
self.send_response(code) | |
self.send_header("Content-Type", "application/json") | |
self.end_headers() | |
def do_GET(self): | |
_type = self.path[3:] | |
logger.info(_type) | |
if _type == '4': | |
response = '{}\n'.format(get_ip_address(ipv6=Falses)) | |
elif _type == 'both': | |
v6 = get_ip_address(ipv6=True) | |
v4 = get_ip_address(ipv6=False) | |
response = 'Your public IPv4 address is {} while your public IPv6 address is {}\n'.format(v4, v6) | |
else: | |
response = '{}\n'.format(get_ip_address()) | |
logger.info(self.client_address) | |
self.set_headers(200) | |
self.wfile.write(response.encode('utf-8')) | |
#self.wfile.close() | |
class v6Server(HTTPServer): | |
address_family = socket.AF_INET6 | |
def main(): | |
if len(sys.argv) == 2: | |
logger.info("Switching to IPV6!") | |
host = '::' | |
port = 5000 | |
server = v6Server((host, port), MyIpServer) | |
else: | |
port = 5000 | |
host = '0.0.0.0' | |
server = HTTPServer((host, port), MyIpServer) | |
server.serve_forever() | |
if __name__ == '__main__': | |
logger.info("Started server!") | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment