The below answer works on my Linux and OS X systems (each having multiple network adapters configured):
[WayBack] bash – How to get the primary IP address of the local machine on Linux and OS X? – Stack Overflow
ip route get 1 | awk '{print $NF;exit}'
For Linux, I have this bash function:
# note the ";exit" lists the first default route interface, as there can be multiple
function nmap-fingerprint_network_of_default_interface() {
default_if=$(ip route list | awk '/^default/ {print $5;exit}')
default_if_cidr=$(ip -o -f inet addr show $default_if | awk '{print $4}')
nmap -sP $default_if_cidr
}
And for OS X this one:
# requires ipcalc
function nmap-fingerprint_network_of_default_interface() {
default_if=$(route -q -n get default | awk '/interface:/ {print $2;exit}')
default_if_address=$(ifconfig $default_if | awk '/inet / {print $2;exit}')
default_if_netmask_hex=$(ifconfig $default_if | awk '/inet / {print $4;exit}')
default_if_network_bit_count=$(ipcalc --nocolor --class $default_if_address $default_if_netmask_hex)
default_if_cidr=$(echo "$default_if_address/$default_if_network_bit_count")
nmap -sP $default_if_cidr
}
These are the variables used:
default_if
: network interface of the default route
default_if_cidr
: IPv4 CIDR of the network interface of the default route (see Classless Inter-Domain Routing: CIDR notation – Wikipedia)
default_if_address
: IPv4 address of network interface of the default route
default_if_netmask_hex
: hexadecimal IPv4 network mask of network interface of the default route
default_if_network_bit_count
: number of set bits in the IPv4 network mask of the network interface of the default route
Links used to get the above functions:
I might have gotten away with a pure bash solution (see [WayBack] Bash script for calculating network and broadcast addresses from ip and netmask or CIDR Notation · GitHub or my post Getting your local IPv4 addresses, netmasks and CIDRs), but the above works and is way shorter, and easier to maintain.
In stead of ipcalc
, subnetcalc
can do the same calculations and also supports IPv6, so that is something for a future try:
–jeroen
Like this:
Like Loading...