Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get gateway address workaround #16

Open
brostosjoined opened this issue Aug 21, 2023 · 1 comment
Open

Get gateway address workaround #16

brostosjoined opened this issue Aug 21, 2023 · 1 comment

Comments

@brostosjoined
Copy link
Contributor

brostosjoined commented Aug 21, 2023

import socket 
import re
import ssl
from urllib.parse import urlparse
from urllib.request import urlopen

# Plucked from https://github.com/tenable/upnp_info/blob/d20a1fda8ca4877d61b89fe7126077a3a5f0b322/upnp_info.py#L23
def get_gateway_ip():
    """Returns the gateway ip of the router if upnp service is available"""
    locations = set()
    location_regex = re.compile("location:[ ]*(.+)\r\n", re.IGNORECASE)
    ssdpDiscover = (
        "M-SEARCH * HTTP/1.1\r\n"
        + "HOST: 239.255.255.250:1900\r\n"
        + 'MAN: "ssdp:discover"\r\n'
        + "MX: 1\r\n"
        + "ST: ssdp:all\r\n"
        + "\r\n"
    )

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.sendto(ssdpDiscover.encode("ASCII"), ("239.255.255.250", 1900))
    sock.settimeout(3)
    try:
        while True:
            data, addr = sock.recvfrom(1024)  # buffer size is 1024 bytes
            location_result = location_regex.search(data.decode("ASCII"))
            if location_result and (location_result.group(1) in locations) == False:
                locations.add(location_result.group(1))
    except socket.error:
        sock.close()
    if locations:
        for location in locations:
            parsed_url = urlparse(location)
            if parsed_url.path.endswith("xml"):
                gateway_ip_address = parsed_url.netloc.split(':')[0]
                context=ssl._create_unverified_context()
                try:
                    with urlopen(f"https://{gateway_ip_address}", context=context) as resp:
                        resp = resp.read().decode()
                        return gateway_ip_address
                except:
                    return gateway_ip_address
            
@brostosjoined
Copy link
Contributor Author

brostosjoined commented Feb 16, 2024

Did a few modification i think now this will work perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant