Created
January 7, 2020 02:41
-
-
Save fricklerhandwerk/4530f2eb097ede9b0044782f03bea6e8 to your computer and use it in GitHub Desktop.
get IP4 network configuration from /proc/net
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# get network configuration for from /proc/net | |
# original: <https://stackoverflow.com/a/14725655/5147619> | |
# WARNING: works only for first adapter listed and only for IP4 | |
# NOTE: ip functions set variables instead of returning to STDOUT | |
hex_to_int() { | |
printf -v $1 "%d\n" 0x${2:6:2}${2:4:2}${2:2:2}${2:0:2} | |
} | |
int_to_ip() { | |
local var=$1 ip | |
shift | |
for ip ;do | |
printf -v $var "%s%s.%s.%s.%s\n" "${!var}" $(($ip>>24)) \ | |
$(($ip>>16&255)) $(($ip>>8&255)) $(($ip&255)) | |
done | |
} | |
mask_len() { | |
local i | |
for ((i=0; i<32 && ( 1 & $2 >> (31-i) ) ;i++));do :;done | |
printf -v $1 "%d" $i | |
} | |
while read -a line ;do | |
if [ ${line[2]} == "00000000" ] && [ ${line[7]} != "00000000" ] ;then | |
hex_to_int net_int ${line[1]} | |
hex_to_int mask_int ${line[7]} | |
if [ $((net_int&mask_int)) == $net_int ] ;then | |
for connections in /proc/net/{tcp,udp} ;do | |
while IFS=': \t\n' read -a conn ;do | |
if [[ ${conn[1]} =~ ^[0-9a-fA-F]*$ ]] ;then | |
hex_to_int ip_int ${conn[1]} | |
[ $((ip_int&mask_int)) == $net_int ] && break 3 | |
fi | |
done < $connections | |
done | |
fi | |
elif [ ${line[1]} == "00000000" ] && [ ${line[7]} == "00000000" ] ;then | |
hex_to_int gateway_int ${line[2]} | |
fi | |
done < /proc/net/route | |
mask_len mask_bits $mask_int | |
int_to_ip address_line $ip_int $net_int $gateway_int $mask_int | |
if [[ -z $PRINT ]] ;then | |
echo $line | |
echo -n "$address_line" | |
else | |
printf -v outForm '%-12s: %%s\\n' \ | |
Interface Address Network Gateway Netmask Masklen | |
printf "$outForm" $line $address_line $mask_bits\ bits | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment