0

Shell Script (Bash) to Edit Output from a Command

I'm trying to make a shell script to determine the range of IP Addresses on my own personal wireless network. When I run this command:

ifconfig

I get this key information:

inet 192.168.1.228

broadcast 192.168.1.255

netmask 255.255.255.0

So now I know that the range is 192.168.1.0-255 (or 192.168.1.0/24). I tried to run this script I made:

#!/bin/bash

ifconfig | awk '/broadcast/ {print $6}'

This will output my max ip range:

192.168.1.255

How can I make this script find my max range like this but instead it writes it like this:

192.168.1.0-255

or

192.168.1.0/24

Any help is much appreciated!

11
  • grep 'broadcast' | awk '{print $6}' doesn't make much sense. awk '/broadcast/ {print $6}' Commented Aug 29, 2017 at 20:56
  • What Unix is this on?
    – Kusalananda
    Commented Aug 29, 2017 at 21:00
  • You do not have enough information to verify your network is /24. Your network very well could be 192.168.1.224/27 based on the information you have provided.
    – jesse_b
    Commented Aug 29, 2017 at 21:02
  • I'm trying to create the output in the form of a variable so I can perform an nmap scan that automatically finds the ip range to scan. That's why i mentioned 0/24 because thats what I used to scan the ip ranges for my network
    – iamr00t
    Commented Aug 29, 2017 at 21:04
  • 1
    I'm creating this tool to be usable for anyone, or at least function properly for anyone that uses it. I do know what my ip range is, but it's because I looked at the provided info from ifconfig...But my script doesn't know what the range is, which is what I'm trying to figure out. I just want to create a script that can take the numbers from 'inet, broadcast and netmask' and piece together a range to be used for future reference. Imagine this as a public tool and not just a personal script, otherwise, I would have just continued a scan a long time ago lol.
    – iamr00t
    Commented Aug 29, 2017 at 21:40

1 Answer 1

2

The simplest solution is to use ip address instead of ifconfig which you should do anyway.

And you can get the netmask from the ifconfig output and calculate the number of 1-bits with this:

echo 255.255.255.0 |
    awk -F. '{print "obase=2;" $1 "*2^24+" $2 "*2^16+" $3 "*2^8+" $4}' |
    bc |
    awk '{ sub("10*$","1", $0); print length($0); }'
2
  • Is this where the '24' comes from when I use 192.168.1.0/24? When I run this command I just get '24', that's why I am asking.
    – iamr00t
    Commented Aug 29, 2017 at 22:02
  • @iamr00t Yes. The /number is the number of 1-bits in the netmask (i.e. 32 minus the size of the local routing domain). 255 is eight 1-bits thus 255.255.255.0 is 24 1-bits. Commented Aug 29, 2017 at 22:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .