ipconfig.co.uk

Scripts and automation

Once you know the commands, the next question is how to use them from a script. These are short, tested patterns that avoid the usual traps: localised ipconfig output, adapter names with spaces, and output formats that change between versions.

Get just the address

Windows · PowerShell
# IPv4 of the adapter that has the default route (the one that reaches the internet)
$ip = (Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway -and $_.NetAdapter.Status -eq 'Up' }).IPv4Address.IPAddress
$ip

# by adapter name
(Get-NetIPAddress -InterfaceAlias 'Ethernet' -AddressFamily IPv4).IPAddress

# MAC of the same adapter
(Get-NetAdapter -Name 'Ethernet').MacAddress

# public IP
(Invoke-RestMethod https://ipconfig.co.uk/ip).Trim()

Alert when the public IP changes

Useful for home servers without a static IP. Store the last value, compare, act. Run it every few minutes from Task Scheduler, cron or launchd.

Linux · Terminal
#!/usr/bin/env bash
# /usr/local/bin/ipwatch.sh  — run from cron: */5 * * * * /usr/local/bin/ipwatch.sh
state="$HOME/.public-ip"
new=$(curl -4 -s --max-time 10 https://ipconfig.co.uk/ip) || exit 0
[[ "$new" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]] || exit 0     # ignore garbage
old=$(cat "$state" 2>/dev/null)
if [[ "$new" != "$old" ]]; then
  echo "$new" > "$state"
  logger -t ipwatch "public IP changed: ${old:-none} -> $new"
  # notify: pick one
  # curl -s -d "IP changed to $new" ntfy.sh/your-topic
  # printf 'Subject: IP changed\n\n%s\n' "$new" | sendmail you@example.com
  # update dynamic DNS, e.g. Cloudflare:
  # curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE/dns_records/$REC" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' --data "{\"content\":\"$new\"}"
fi

Be polite to whatever service you poll: every five minutes is plenty. This site's /ip endpoint is fine for that; it returns only the address with no rate limit for reasonable use.

Export a network report for a ticket

Windows · Command Prompt
@echo off
set out=%USERPROFILE%\Desktop\netreport-%COMPUTERNAME%.txt
(
  echo === %DATE% %TIME% %COMPUTERNAME% ===
  echo.
  echo --- ipconfig /all --- & ipconfig /all
  echo --- route print -4 --- & route print -4
  echo --- arp -a --- & arp -a
  echo --- netsh wlan show interfaces --- & netsh wlan show interfaces
  echo --- DNS test --- & nslookup example.com & nslookup example.com 1.1.1.1
  echo --- ping --- & ping -n 4 1.1.1.1 & ping -n 4 example.com
  echo --- tracert --- & tracert -d -h 15 1.1.1.1
  echo --- netstat -e --- & netstat -e
  echo --- excluded ports --- & netsh int ipv4 show excludedportrange protocol=tcp
) > "%out%" 2>&1
echo Saved to %out%
start notepad "%out%"
Windows · PowerShell
$out = "$env:USERPROFILE\Desktop\netreport-$env:COMPUTERNAME.txt"
& {
  Get-Date; $env:COMPUTERNAME
  '--- adapters ---'; Get-NetAdapter | Format-Table Name, Status, LinkSpeed, MacAddress -AutoSize
  '--- config ---'; Get-NetIPConfiguration -Detailed
  '--- routes ---'; Get-NetRoute -AddressFamily IPv4 | Sort-Object RouteMetric | Format-Table -AutoSize
  '--- neighbours ---'; Get-NetNeighbor -AddressFamily IPv4 | Where-Object State -ne Unreachable | Format-Table -AutoSize
  '--- dns ---'; Get-DnsClientServerAddress; Resolve-DnsName example.com -ErrorAction Continue
  '--- tests ---'; Test-NetConnection 1.1.1.1; Test-NetConnection example.com -Port 443
  '--- wifi ---'; netsh wlan show interfaces
} *> $out
Invoke-Item $out

Wait for the network before doing something

Linux · Terminal
#!/usr/bin/env bash
# wait up to 60 s for a default route and working DNS
for i in $(seq 1 60); do
  if ip route show default | grep -q . && getent hosts example.com >/dev/null; then
    echo "network up"; break
  fi
  sleep 1
done
# systemd users: order the unit After=network-online.target and Wants=network-online.target instead

Toggle between DHCP and a static profile

Windows · Command Prompt
@echo off
rem usage: netmode static | netmode dhcp   (run as administrator)
set NIC=Ethernet
if /i "%1"=="static" (
  netsh interface ipv4 set address name="%NIC%" static 192.168.1.50 255.255.255.0 192.168.1.1
  netsh interface ipv4 set dnsservers name="%NIC%" static 1.1.1.1 primary
  netsh interface ipv4 add dnsservers name="%NIC%" 1.0.0.1 index=2
) else (
  netsh interface ipv4 set address name="%NIC%" source=dhcp
  netsh interface ipv4 set dnsservers name="%NIC%" source=dhcp
)
ipconfig | findstr /c:"IPv4" /c:"Gateway"

Scheduled DHCP renew or adapter bounce

Occasionally a flaky driver or an ISP that requires periodic renewals justifies this. Prefer fixing the cause.

Windows · Command Prompt
schtasks /create /tn "Renew DHCP" /sc daily /st 04:00 /ru SYSTEM /tr "ipconfig /renew"
schtasks /create /tn "Bounce Wi-Fi" /sc daily /st 04:05 /ru SYSTEM /tr "powershell -NoProfile -Command Restart-NetAdapter -Name Wi-Fi"
schtasks /delete /tn "Renew DHCP" /f

Parsing tool output safely

  • Prefer structured output. ip -j (JSON), PowerShell objects, nmcli -t -f FIELDS (terse, colon-separated), networkctl --json=short, ipconfig getoption on macOS. Parse ipconfig or ifconfig text only as a last resort.
  • Assume names have spaces ("Wired connection 1", "Local Area Connection 2", "USB 10/100/1000 LAN"). Quote every variable.
  • Assume more than one interface and more than one address per interface. VPNs, Docker and virtual machines add both. Pick by default route (ip route get, Get-NetIPConfiguration | ? IPv4DefaultGateway) rather than "the first one".
  • Expect no output on success from Unix commands and check exit codes ($?, $LASTEXITCODE).
  • Time out network calls (curl --max-time, Invoke-RestMethod -TimeoutSec) so a script does not hang forever when the network is the very thing that is broken.
  • Log with timestamps. logger on Linux/macOS, Write-EventLog on Windows, or plain date >> log. When a network problem is intermittent, the timestamp of the last good run is the most useful fact you will have.

Related pages

Last reviewed . Command syntax verified against Windows 11, Ubuntu 24.04, macOS 15 and FreeBSD 14 unless noted otherwise.

Spotted a mistake or a switch we have missed? Every page on this site is written to be checked against real output, so please test on your own machine and compare.