Skip to content

Instantly share code, notes, and snippets.

@hypevhs
Created October 11, 2021 20:23
Show Gist options
  • Save hypevhs/8c99575c0cb60ff32a7516ea795193d6 to your computer and use it in GitHub Desktop.
Save hypevhs/8c99575c0cb60ff32a7516ea795193d6 to your computer and use it in GitHub Desktop.
Convert /proc/net/route IP from hex to quad-dotted representation
#!/usr/bin/env bash
# not zsh portable
set -euxo pipefail
# Usage: ... | hex_to_ip
# Reads stdin and converts IPs from hex to quad-dotted representation.
function hex_to_ip {
if [[ -n "$1" ]]; then echo "$0: Too many arguments">&2; return 1; fi
# might break on big endian?
sed -r 's/(..)(..)(..)(..)/0x\4 0x\3 0x\2 0x\1/;s/.*/printf "%d.%d.%d.%d" &/e'
}
# Usage: get_gateway_for_iface IFACE
# Prints the hex IP of the gateway associated with the interface IFACE.
# If there are multiple, picks the first.
function get_gateway_for_iface {
if [[ -z "$1" ]]; then echo "Missing argument">&2; return 1; fi
awk '$1 == "'"$1"'" && $3 != "00000000" { found=1; print $3 } END { exit !found }' /proc/net/route | head -n1
}
# Example: convert hex IP to quad-dotted IP
# $ hex_to_ip <<< 4032A8C0
# 192.168.50.64
# Example: get gateway for eno1
# $ get_gateway_for_iface eno1
# 0101A8C0
# $ get_gateway_for_iface eno1 | hex_to_ip
# 192.168.1.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment