Terminal command to return network class

command lineNetworkterminal

I'm trying to construct myself a primitive network scanner, and I understand that there are multiple network classes and it has become necessary for my program to determine exactly what class of network the workstation is currently connected to.

I have trialled a few options which i consider to be needlessly complicated, such as truncating various commands such as ifconfig, however these methods are arduous and messy.

Is there a single Terminal command which can return simple output such as 10.0.0.0, thereby identifying the network class?

Best Answer

You can try something like this:

#!/bin/bash                                                                                                                                   

IPS=$(ifconfig -a | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1' | sed 's/127.0.0.1//')

FIRST=$(echo "${IPS%%.*}")

case 1 in
$(($FIRST <= 127))) echo Class A ;;
$(($FIRST <= 191))) echo Class B ;;
$(($FIRST <= 223))) echo Class C ;;
$(($FIRST <= 239))) echo Class D ;;
$(($FIRST <= 255))) echo Class E ;;
*) echo Something wrong! ;;
esac

If You want only the IP, echo the $IPS variable.