From 6aaa0351ac8791fa0052e2c0972c0dc20b179f74 Mon Sep 17 00:00:00 2001 From: Maeve Gallagher Date: Sat, 3 Oct 2026 06:39:17 +0300 Subject: [PATCH] chore(release): bump version to v1.0.1 --- README.md | 42 +++++++++ catalog/strings.json | 38 ++++++++ main.py | 12 +++ manifest.json | 13 +++ src/__pycache__/catalog.cpython-313.pyc | Bin 0 -> 2916 bytes src/__pycache__/cli.cpython-313.pyc | Bin 0 -> 5991 bytes src/__pycache__/resolver.cpython-313.pyc | Bin 0 -> 6051 bytes src/catalog.py | 45 ++++++++++ src/cli.py | 94 +++++++++++++++++++ src/resolver.py | 110 +++++++++++++++++++++++ 10 files changed, 354 insertions(+) create mode 100644 README.md create mode 100644 catalog/strings.json create mode 100644 main.py create mode 100644 manifest.json create mode 100644 src/__pycache__/catalog.cpython-313.pyc create mode 100644 src/__pycache__/cli.cpython-313.pyc create mode 100644 src/__pycache__/resolver.cpython-313.pyc create mode 100644 src/catalog.py create mode 100644 src/cli.py create mode 100644 src/resolver.py diff --git a/README.md b/README.md new file mode 100644 index 0000000..8f6c7c3 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# MyIP + +Zero-Latency Local (LAN) and Public (WAN) IP Address Resolver for the Gravitiny Ecosystem. + +Author: **Maeve Gallagher** (`maevecodes`) + +--- + +## Features + +- **Instant Local Resolution:** Uses zero-packet UDP kernel routing lookup to determine local IPv4 instantly. +- **Fast Public Resolution:** Multi-provider fallback (`ipify`, `icanhazip`, `ifconfig.me`) with aggressive 2.0s timeouts. +- **Single-Line Output:** Formatted cleanly for direct terminal reading and shell piping. +- **JSON Mode:** `-j` / `--json` flag for scripting, monitoring, and CI/CD pipelines. +- **Verbose Network Diagnostic:** `-v` / `--verbose` mode shows host interfaces and ISP geolocation details. + +--- + +## Usage + +```bash +# Default single-line output +myip + +# Output only public IP +myip --public + +# Output only local IP +myip --local + +# JSON output +myip --json + +# Verbose geolocation and interface report +myip --verbose +``` + +--- + +## License + +MIT License. diff --git a/catalog/strings.json b/catalog/strings.json new file mode 100644 index 0000000..1237e0c --- /dev/null +++ b/catalog/strings.json @@ -0,0 +1,38 @@ +{ + "app": { + "name": "MyIP", + "tagline": "Zero-Latency IP Address Resolver & Network Diagnostic Utility", + "version_output": "{name} v{version} by {author}" + }, + "cli": { + "usage": "Usage: myip [options]", + "options_title": "Options:", + "opt_help": "Show this help message and exit", + "opt_version": "Show version information and exit", + "opt_json": "Output results as structured JSON", + "opt_local": "Output local LAN IP address only", + "opt_public": "Output public WAN IP address only", + "opt_verbose": "Show detailed interface list and geolocation metadata" + }, + "output": { + "single_line": "Local IP: {local_ip} | Public IP: {public_ip}", + "local_only": "{local_ip}", + "public_only": "{public_ip}", + "unknown": "Unavailable", + "resolving": "Resolving network configuration...", + "verbose_header": "Network Configuration & Public Geolocation:", + "field_hostname": "Hostname", + "field_local_ip": "Local IP (LAN)", + "field_public_ip": "Public IP (WAN)", + "field_city": "City", + "field_region": "Region", + "field_country": "Country", + "field_org": "ISP / Organization", + "field_timezone": "Timezone", + "interfaces_header": "Active Network Interfaces:" + }, + "errors": { + "public_resolution_failed": "Failed to resolve public IP address.", + "local_resolution_failed": "Failed to resolve local IP address." + } +} diff --git a/main.py b/main.py new file mode 100644 index 0000000..bab2477 --- /dev/null +++ b/main.py @@ -0,0 +1,12 @@ +import sys +from pathlib import Path + +# Add applet root to sys.path +applet_root = Path(__file__).resolve().parent +if str(applet_root) not in sys.path: + sys.path.insert(0, str(applet_root)) + +from src.cli import run_cli + +if __name__ == "__main__": + sys.exit(run_cli()) diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..8628a0b --- /dev/null +++ b/manifest.json @@ -0,0 +1,13 @@ +{ + "id": "myip", + "name": "MyIP", + "version": "1.0.1", + "description": "Zero-latency local and public IP resolver with single-line stdout and JSON formatting.", + "author": "Maeve Gallagher ", + "license": "MIT", + "runtime": "python", + "entrypoint": "main.py", + "shims": ["myip", "ipip"], + "tags": ["network", "ip", "diagnostics", "security", "utilities"], + "network": "online" +} diff --git a/src/__pycache__/catalog.cpython-313.pyc b/src/__pycache__/catalog.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c993f9dcb0f19fe023083016776af3d063a0420 GIT binary patch literal 2916 zcmb_e-A^3X6~FVfGt2I>z?x#4jTvklJd&XnhAbt)n*Re-A7DZ&(`%$g%2VEOXk@ETJ$H5oW8^9? zxvM?*>)dnCJs-a_JF!>;g7(eK7t`k@guY{wpo#Ut&Py=3hIFKJ=Mb*-9OhuopW|N< zu<(kAMHL-HN0BZZM!Gn_*G^(7CmlrtbulgROnFq&3yL~qn( z7>PKl$8{yA=wbMWa!P+lZ(!@w9FFKn0L51UTulATwHzpq*~2GuE>c^j*RGFHduUVc?ID;3A~dNWip>MRxq zGJ+<+fc<$7i zssHD8Fa(#;BpNnKF7Zs)vZ+L7D>lZ=98@+8*S=^NG-j~Z2k&Hlwj2Vd49hVIF$}_9 zpw82mMuu`(Vq=msozs=`xlx;3@XD235u3j)c_nvl&!}cUlAD<;RdNJdxw;j5D|0x? zZf||eLA`Zd*cKTA@^Bt)Mj97~7lzj(>Q=JzM$fIpdUE)-wUK34&vP?{Yt(MW`wV5J-d2_u-7~0zAPlfFczY(J2V+NBc$8 ziB6*6{yccGz^kYOsqibJVW9&RI4zW+ay{5CMQd43dZ$U*r5wH_&3c8NL5-t|?ONqL zAcPj7e3?+OVtVJPoG)S5oUy5FP7!}aF^odVu^~&u>2k@XA^UeF;sJlTV!N=$($qjg;jUmRB;3NZWPg9?#KTUr!1`#TH(FS!YD-~Og^L0Gr~;NTO|(iO8p0*xJqAeJU~Q#311 zGD!1V5I#Yen2-){y!I^YnZWbLS$4=3$BzO2@&v-C3q>G&vf>o*P41#>Rtz-h0zN=e zK0~=)08@!noRa5zn>LilF0zVwD2r5pfYU(RJ94G*ei*eL-flo@_j*U)2V^Pr{^dJL`nC)N zvjC%^3l~jXB-UPwGea>b*{J~WE8G)2#(*WTxGNli#D0?3;46cNROUyyXSgo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FqAu< zi*5CNv6QJoA{LsjFc?;Cc(nP9LP5KO(&#&9xeqx z0%=(F8?h1s)fma4fQmjSp}4}rPXR#r>`@9j`0#Q%mQB&4>?rI&=Q}q5Z_r4c?rUKC x8d(1d+Wrm>{23g4ZnEi4>%QARuG87?2i8uk8-6{I_Z)r-kYcm$UrMV`{|_oBx`+S( literal 0 HcmV?d00001 diff --git a/src/__pycache__/resolver.cpython-313.pyc b/src/__pycache__/resolver.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8143cb986144fd22ddc064ce702516591b33d824 GIT binary patch literal 6051 zcmai2Yit|GwVvJOn|e_sMap`u^@v10C?&G%M=VD)ZObpoHrI^pYdX9uYDKM0Et%Ps zW2r^a7U+e3+P4TSwFROe1tQ@Vu#1bLPWz*Bj3P?%M>L(1T^qRtdT{~&V=4m%>_7L+ zl1tHw><+;*k8|dnd7Sy?%x+Xx+7P7d^y-xt)d>BARPYNWAh0Mwy?;HS`o+WK%8MWUC@NBamr_WLMmfEgUSS?S=De@ zj47(&lqf5z<#b9BlM~gN|YGrKQX=o&& zFbe5jP$t1qyI~w8u|&dJD3?=xUpZ|rB`QpH71{hwgu+zFUM^iIbBwN4mz@BqFeTIA zVer$(#iDj_?U!3#T9K;n>uyE*h$Omf?P|7@4Ac5JUK%&7W0-1(wT~NjqFz)QBdo+E z&7u}q3l@zX8Dd({B()P=s?c?t5f6JuB*xB7qSx``MxF07&2fhXMZnXdB*?5XC9o+h zPV;z{P0lFe$r*6#f`cDFb8T12uV-XYinHOvXIMEIyDBIw25HiiNG7k&r2Ia5&b-&J z{hpkG@nPZ|bA~tH+T$OavyyB8esB7$s;QtrH3yDHkB=QWr`ovF!IRO$BcZ^kY6jPr z1V9gaTu_Lh#7_&VO;&iU$RCKxlxjV4JtkAq7OUg2!*i?YKbwAi?V}$r{`j}ovi-y9 z{^5s?!0Oq**EnujZ(0}nAJ%l|+;z7u-@N>b=+fD=yYmM9t<$|Q{?YW}^zzYc^I*Dp zFx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W3~OCs}L7T&WTB=J=i?s@@F@-d;e{AnE*k|e?=-w@bo zLE$HOh4-uWu*6^E#RNZ|5PVkbh0&>&QY3CI-J7Z*CMvV!;Ts19t96TEjI@bXpS0n!OP1!==9tgu0oHp7-gA-chXgu9FAHIQ9Vtwdo|ld;Hx zAVEX}@sp?s(`tp7io(Z^2@wPZnaqpCK&4a&hH6MK1m9T3ld@1y)37BTDrb_VmQ!## zw2;W<$vWH8&bExRW8RX3nyVx2>d3e{=dF*O^;u`f17}AD;v@@%PxU)MDg<4?VueEo~po{c>)({kCt#_g_8P?gQ!W19#77x{qX9jxHE- zojspk|M>bHQ>JrIwsYj}u2s`#2Nnzq?=Dv4e0{gQE8aU@8Qydw7=dYwA zS3&mTVs-9~?oX#ao?4#yB$<8V{9V_dy`OnkJO0!Hm9@j`XW#wuB*=vq?YW-*+k02` z-Z_!!c_-V$t?pX0rGp&s{w?k8`nIKOdE)le%G4d@wzMLx8osdHv#fct!)MdOXLAF) z{$Tl?<*w_$tFi;!YWo*m_qx{hWDao)hnE`CjeR+9(=#`!JD7G4l+(-9LZ)v1i9GX6BDQ^6tE0$hEXB1r|S8dVg{5Mn%rq z@{O}U=W4ul>gK7X#)mF{&gETbOuOF5y86jSkvQ(#EeTicq8Nq?7r&mIAs04;8A2HE7sZt6HK_@);u< zRc+DebaG-QLCO`;==(E#qR6R^MkhrqD+&0JBPD@tjz%Yvv1k;(0VBjmfv6Sa86(C3 zIj52naL^U3;R|3?f|uoDvvCrDLct{dEdY;(NhEB>VWPwxjTY2Ic?I4-<1=uE!OD5y zZNMLC#}|{3S0iR9$Ug=0ALws};6DvUuW8-jf)%&!%vspHk!gZ@J$!&L)#hoJv0 None: + base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + catalog_path = os.path.join(base_dir, "catalog", "strings.json") + if os.path.exists(catalog_path): + with open(catalog_path, "r", encoding="utf-8") as f: + self._catalog = json.load(f) + else: + self._catalog = {} + + def get(self, key_path: str, default: str = "") -> str: + parts = key_path.split(".") + current = self._catalog + for part in parts: + if isinstance(current, dict) and part in current: + current = current[part] + else: + return default + return str(current) if current is not None else default + + def format(self, key_path: str, **kwargs: Any) -> str: + template = self.get(key_path, "") + try: + return template.format(**kwargs) + except KeyError: + return template + + +catalog = StringCatalog() diff --git a/src/cli.py b/src/cli.py new file mode 100644 index 0000000..1bedafc --- /dev/null +++ b/src/cli.py @@ -0,0 +1,94 @@ +import json +import sys +from typing import List, Optional + +from src.catalog import catalog +from src.resolver import IPResolver + + +def print_help() -> None: + print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}") + print() + print(catalog.get("cli.usage")) + print() + print(catalog.get("cli.options_title")) + print(f" -h, --help {catalog.get('cli.opt_help')}") + print(f" -V, --version {catalog.get('cli.opt_version')}") + print(f" -j, --json {catalog.get('cli.opt_json')}") + print(f" -l, --local {catalog.get('cli.opt_local')}") + print(f" -p, --public {catalog.get('cli.opt_public')}") + print(f" -v, --verbose {catalog.get('cli.opt_verbose')}") + + +def run_cli(args: Optional[List[str]] = None) -> int: + if hasattr(sys.stdout, "reconfigure"): + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + + raw_args = args if args is not None else sys.argv[1:] + + if "-h" in raw_args or "--help" in raw_args: + print_help() + return 0 + + if "-V" in raw_args or "--version" in raw_args or "-v" in raw_args and len(raw_args) == 1 and raw_args[0] == "-v": + # Check if version vs verbose + if "--version" in raw_args or "-V" in raw_args: + print(catalog.format("app.version_output", name="MyIP", version="1.0.0", author="Maeve Gallagher")) + return 0 + + is_json = "-j" in raw_args or "--json" in raw_args + is_local_only = "-l" in raw_args or "--local" in raw_args + is_public_only = "-p" in raw_args or "--public" in raw_args + is_verbose = "-v" in raw_args or "--verbose" in raw_args + + if is_local_only: + local_ip = IPResolver.get_local_ip() + if is_json: + print(json.dumps({"local_ip": local_ip}, indent=2)) + else: + print(local_ip) + return 0 + + if is_public_only: + public_ip = IPResolver.get_public_ip() or catalog.get("output.unknown") + if is_json: + print(json.dumps({"public_ip": public_ip}, indent=2)) + else: + print(public_ip) + return 0 + + if is_verbose: + info = IPResolver.get_verbose_info() + if is_json: + print(json.dumps(info, indent=2)) + else: + print(catalog.get("output.verbose_header")) + print("-" * 50) + print(f" {catalog.get('output.field_hostname'):<20}: {info['hostname']}") + print(f" {catalog.get('output.field_local_ip'):<20}: {info['local_ip']}") + print(f" {catalog.get('output.field_public_ip'):<20}: {info['public_ip']}") + print(f" {catalog.get('output.field_country'):<20}: {info['country']}") + print(f" {catalog.get('output.field_region'):<20}: {info['region']}") + print(f" {catalog.get('output.field_city'):<20}: {info['city']}") + print(f" {catalog.get('output.field_org'):<20}: {info['org']}") + print(f" {catalog.get('output.field_timezone'):<20}: {info['timezone']}") + if info["interfaces"]: + print() + print(f" {catalog.get('output.interfaces_header')}") + for iface in info["interfaces"]: + print(f" - {iface}") + return 0 + + # Default output: single clean line + local_ip = IPResolver.get_local_ip() + public_ip = IPResolver.get_public_ip() or catalog.get("output.unknown") + + if is_json: + print(json.dumps({"local_ip": local_ip, "public_ip": public_ip}, indent=2)) + else: + print(catalog.format("output.single_line", local_ip=local_ip, public_ip=public_ip)) + + return 0 diff --git a/src/resolver.py b/src/resolver.py new file mode 100644 index 0000000..7d0e229 --- /dev/null +++ b/src/resolver.py @@ -0,0 +1,110 @@ +import json +import socket +import urllib.request +from typing import Any, Dict, List, Optional + + +class IPResolver: + """Fast, zero-overhead local and public IP address resolver.""" + + PUBLIC_PROVIDERS = [ + "https://api.ipify.org", + "https://icanhazip.com", + "https://ifconfig.me/ip", + "https://ipecho.net/plain" + ] + + GEOLOCATION_PROVIDERS = [ + "https://ipinfo.io/json", + "http://ip-api.com/json" + ] + + @staticmethod + def get_local_ip() -> str: + """Determines the primary outbound local IPv4 address using UDP socket routing lookup.""" + try: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + # Does not establish a connection; triggers kernel routing table selection + s.connect(("8.8.8.8", 80)) + ip = s.getsockname()[0] + if ip and not ip.startswith("127."): + return ip + except Exception: + pass + + try: + hostname = socket.gethostname() + ip = socket.gethostbyname(hostname) + if ip: + return ip + except Exception: + pass + + return "127.0.0.1" + + @classmethod + def get_public_ip(cls, timeout: float = 2.0) -> Optional[str]: + """Resolves public WAN IP address using lightweight HTTP endpoints.""" + req_headers = {"User-Agent": "curl/7.68.0"} + for url in cls.PUBLIC_PROVIDERS: + try: + req = urllib.request.Request(url, headers=req_headers) + with urllib.request.urlopen(req, timeout=timeout) as resp: + if resp.status == 200: + ip = resp.read().decode("utf-8").strip() + if ip and len(ip) <= 45: # Valid IPv4 or IPv6 string + return ip + except Exception: + continue + return None + + @classmethod + def get_verbose_info(cls) -> Dict[str, Any]: + """Collects full host, network interface, and public geolocation metadata.""" + local_ip = cls.get_local_ip() + public_ip = cls.get_public_ip() + hostname = socket.gethostname() + + info: Dict[str, Any] = { + "hostname": hostname, + "local_ip": local_ip, + "public_ip": public_ip or "Unavailable", + "city": "Unavailable", + "region": "Unavailable", + "country": "Unavailable", + "org": "Unavailable", + "timezone": "Unavailable", + "interfaces": [] + } + + # Query geolocation + for geo_url in cls.GEOLOCATION_PROVIDERS: + try: + req = urllib.request.Request(geo_url, headers={"User-Agent": "curl/7.68.0"}) + with urllib.request.urlopen(req, timeout=2.5) as resp: + if resp.status == 200: + data = json.loads(resp.read().decode("utf-8")) + info["city"] = data.get("city") or info["city"] + info["region"] = data.get("region") or data.get("regionName") or info["region"] + info["country"] = data.get("country") or data.get("countryCode") or info["country"] + info["org"] = data.get("org") or data.get("isp") or info["org"] + info["timezone"] = data.get("timezone") or info["timezone"] + if not public_ip and (data.get("ip") or data.get("query")): + info["public_ip"] = data.get("ip") or data.get("query") + break + except Exception: + continue + + # Enumerate host addresses + try: + addr_info = socket.getaddrinfo(hostname, None) + seen_ips = set() + for item in addr_info: + ip_candidate = item[4][0] + if ip_candidate not in seen_ips: + seen_ips.add(ip_candidate) + info["interfaces"].append(ip_candidate) + except Exception: + pass + + return info