commit bf4a5097944084990f3ffee82488798f32c23840 Author: Maeve Gallagher Date: Sat Oct 3 05:52:34 2026 +0300 feat: initial release of myip v1.0.0 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..2abf078 --- /dev/null +++ b/manifest.json @@ -0,0 +1,13 @@ +{ + "id": "myip", + "name": "MyIP", + "version": "1.0.0", + "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 0000000..8c993f9 Binary files /dev/null and b/src/__pycache__/catalog.cpython-313.pyc differ diff --git a/src/__pycache__/cli.cpython-313.pyc b/src/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000..c0ea04d Binary files /dev/null and b/src/__pycache__/cli.cpython-313.pyc differ diff --git a/src/__pycache__/resolver.cpython-313.pyc b/src/__pycache__/resolver.cpython-313.pyc new file mode 100644 index 0000000..8143cb9 Binary files /dev/null and b/src/__pycache__/resolver.cpython-313.pyc differ diff --git a/src/catalog.py b/src/catalog.py new file mode 100644 index 0000000..e557aa5 --- /dev/null +++ b/src/catalog.py @@ -0,0 +1,45 @@ +import json +import os +from typing import Any, Dict + + +class StringCatalog: + """Centralized string catalog loader for MyIP applet.""" + + _instance = None + _catalog: Dict[str, Any] = {} + + def __new__(cls): + if cls._instance is None: + cls._instance = super(StringCatalog, cls).__new__(cls) + cls._instance._load_catalog() + return cls._instance + + def _load_catalog(self) -> 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