How to Programmatically Get an IP Address in Python, JavaScript, and Bash

Get IP Address: Methods for Windows, macOS, Linux, and Mobile

What “IP address” means

An IP address is a numeric identifier assigned to a device on a network. IPv4 uses dotted-decimal (e.g., 192.0.2.1); IPv6 uses hexadecimal colon-separated format (e.g., 2001:db8::1). Devices typically have:

  • Private (local) IP: assigned by your router for use inside a LAN.
  • Public (external) IP: the address your network presents to the internet (may be shared via NAT).

How to get your IP on each platform

Windows

  • Private (local): open Command Prompt and run ipconfig. Look for “IPv4 Address” under the active adapter.
  • Public (external): visit an online IP-check service in a browser or run curl ifconfig.me in PowerShell/WSL.

macOS

  • Private: open Terminal and run ipconfig getifaddr en0 (Wi‑Fi) or use ifconfig and find the active interface’s inet entry.
  • Public: visit an online IP-check site in a browser or run curl ifconfig.me in Terminal.

Linux

  • Private: open Terminal and run ip addr show and look for inet under the active interface (e.g., eth0, wlan0), or use hostname -I.
  • Public: use curl ifconfig.me, curl icanhazip.com, or check a web-based IP checker.

Android

  • Private: Settings → Network & internet → Wi‑Fi → tap connected network → view IP address (paths vary by Android version).
  • Public: use a browser to visit an IP-check site or use a network utility app.

iOS

  • Private: Settings → Wi‑Fi → tap the information (i) next to the connected network → view IP Address.
  • Public: open Safari and visit an IP-check site.

Programmatic methods (brief)

  • Shell: curl ifconfig.me or curl icanhazip.com for public IP.
  • Python: use requests to call an external API (e.g., requests.get(’https://ifconfig.me’).text) or use socket.gethostbyname(socket.gethostname()) for local address (may return 127.0.0.1 in some setups).
  • JavaScript (browser): fetch(’https://api.ipify.org?format=json’) for public IP. Node.js: use OS/network modules or external service.

Notes and common pitfalls

  • NAT and routers mean multiple devices share a single public IP; local IPs differ from public.
  • localhost or 127.0.0.1 is not your device’s network IP.
  • Some commands vary by distro, OS version, or interface name.
  • Public IP-checking services are simplest but rely on third-party endpoints.

If you want, I can provide exact commands for your OS/version or short example scripts for Python, Bash, or JavaScript.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *