Layer 3 discovery with Ping

If ICMP (Internet Control Message Protocol) is not blocked – the ping command is one of my most used tools.

Example

# Syntax
$ ping -c <number> <target>

# Example
$ ping -c 1 192.168.0.1

Usage

With a small bash-script it is possible to identify all hosts that respond to ICMP requests.

#!/usr/bin/env bash

# define shell options
set -e
set -u

# define magic variables
declare -r FILE_NAME=$(basename "$0")
declare -r -i SUCCESS=0
declare -r -i NO_ARGS=84
declare -r -i BAD_ARGS=85

# usage function
function fc_usage() {
  printf "Usage: %s -i 192.168.1.0" "$FILE_NAME"
  printf " [-h]\n"
}

# help function
function fc_help() {
  fc_usage
}

# error communication functions
function fc_no_args() {
  printf "Error: no arguments supplied\n"
  exit "$NO_ARGS"
}

function fc_bad_args() {
  printf "Error: wrong arguments supplied\n"
}

# check script arguments
if [ "$#" -eq 0 ]; then
  fc_no_args
fi

while getopts "hi:" OPTION; do
  case "$OPTION" in
      h)
        fc_help exit "$SUCCESS" ;;
      i)
        PREFIX=$(echo "$OPTARG" | cut -d '.' -f 1-3) ;;
      *)
        fc_bad_args
        fc_usage exit "$BAD_ARGS" ;;
  esac
done 

# main
for ADDR in $(seq 1 254); do
  ping -c 1 "$PREFIX"."$ADDR" | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 &
done

# exit
exit "$SUCCESS"