Categories
powershell

ipcalc in powershell

Last day I wrote how to do it in AIX or Linux ip calc with ifconfig

It isn’t that different in PowerShell, the fun is to the calculation yourself. For translating 0.0.0.0 in 0, we can use [IPADDRESS].

Let’s try…

$ip = [IPADDRESS](
(Get-NetIPAddress -AddressFamily "IPv4" -InterfaceAlias "Ethernet*").
ipaddress)

$prefix = (
Get-NetIPAddress -AddressFamily "IPv4" -InterfaceAlias "Ethernet*").
prefixlength

The length and the ip of the current interface. In my case I have only one

PS> $ip
Address : 1677830336
AddressFamily : InterNetwork
IPAddressToString : 192.168.1.100
PS> $prefix
24

with a prefix length of 24, we need a netmask of 24 bits

11111111.11111111.11111111.00000000

which is

11111111.11111111.11111111.11111111 --> 2^32-1
-
11111111 --> 2^(32-24)-1

to do the math

$netmask=[IPADDRESS]([Math]::Pow(2,32)-[Math]::Pow(2,32-$prefix))
IPAddressToString : 255.255.255.0

let’s bitand

$netid = [IPADDRESS]($ip.Address -band $netmask.address)
IPAddressToString : 192.168.1.0

Categories
linux unix

network ip calculation with ifconfig

Most *nix are different. I’ll start with a plain Linux output

ifconfig eth0
eth0: flags=4163  mtu 1500
        inet 93.184.216.34  netmask 255.255.255.0  broadcast 93.184.216.255

to get the network ip, I just bitwise-and the inet and the netmask. To do it with the shell, I convert the ip to an integer and use the & (AND) operator

IP=$(ifconfig eth0|grep inet|awk '{print $2}')
NM=$(ifconfig eth0|grep inet|awk '{print $4}')

I get my IP=93.184.216.34 and NM=255.255.255.0 out of the ifconfig output

IPDEC=0;IFS=. ;for f in $IP;do ((IPDEC*=256));((IPDEC+=$f));done
NMDEC=0;IFS=. ;for f in $NM;do ((NMDEC*=256));((NMDEC+=$f));done

By converting the IP-base-256 address, I get IPDEC=1572395042 and NMDEC=4294967040 in decimal

NWDEC=$((IPDEC&NMDEC))

That’s simple. My network IP is 1572395008

Let’s print it

NW=$((NWDEC/256/256/256)).$((NWDEC/256/256%256)).$((NWDEC/256%256)).$((NWDEC%256))
NW=93.184.216.0

Thanks for reading me that far. Ok let blogger Mathieu Trudel-Lapierre tell you : If you’re still using ifconfig, you’re living in the past

ip addr

ip shows your ip, and ipcalc do the calculation

ipcalc -n "$(ip -o -4  -br address show eth0 |awk '{print $3}')"
NETWORK=93.184.216.0