#!/bin/bash
# 从CIDR网段随机生成一个可用的主机IP地址

ip2int() {
  local IFS=.
  local a b c d
  read -r a b c d <<< "$1"
  echo $(( (a << 24) + (b << 16) + (c << 8) + d ))
}

int2ip() {
  local n=$1
  echo "$(( (n >> 24) & 255 )).$(( (n >> 16) & 255 )).$(( (n >> 8) & 255 )).$(( n & 255 ))"
}

rand_u32() {
  od -An -N4 -tu4 /dev/urandom | tr -d ' '
}

rand_between() {
  local min=$1
  local max=$2
  local span=$(( max - min + 1 ))
  local r
  r=$(rand_u32)
  echo $(( min + (r % span) ))
}

rand_host_ip() {
  local cidr=$1
  local out net bcast n b start end ipn

  out=$(ipcalc -n -b "$cidr" 2>/dev/null) || {
    echo "无效网段: $cidr" >&2
    return 1
  }

  net=$(printf '%s\n' "$out" | awk '/^Network:/{print $2}' | cut -d/ -f1)
  bcast=$(printf '%s\n' "$out" | awk '/^Broadcast:/{print $2}')

  n=$(ip2int "$net")
  b=$(ip2int "$bcast")

  start=$(( n + 1 ))
  end=$(( b - 1 ))

  if (( end < start )); then
    echo "该网段没有可用主机地址: $cidr" >&2
    return 2
  fi

  ipn=$(rand_between "$start" "$end")
  int2ip "$ipn"
}

if [ $PING_CHECK -eq 1 ]; then
  while true; do
    ip=$(rand_host_ip "$1") || exit 1
    if ! ping -c 1 -W 1 "$ip" >/dev/null 2>&1; then
      echo "$ip"
      exit 0
    fi
  done
else
  rand_host_ip "$1"
fi
