How to map a client ID to an IPv4 address?

Viewed 75

I have a bash script that creates 1024 clients. I have to allocate IPv4 addresses from a given subnet to those clients accordingly. The challenge is how to map the client ID to a IPv4 address.

COUNTER=0
for ip in 172.16.10{0..4}.{0..255} 
do
  COUNTER=$((COUNTER+1))
  FILE_NUMBER="${COUNTER}"
  CLIENT_IPV4="${ip}"
  echo "###Client ${COUNTER}###
        Address = ${CLIENT_IPV4}/32" >"$HOME/${FILE_NUMBER}.conf"
done

While this seems ok at first, later on I need to know that Client 500, corresponds to the IP address 172.16.101.243. Is there any clever way to do that?

I came up with this solution, but I'm not sure if this is a good one:

function map_client_to_ipv4() {
  val=$(($1/256))
  mod=$(($1%256))
  ret_val=172.16.10${val}.$((mod-1))
}

map_client_to_ipv4 500
echo $ret_val
2 Answers

I suggest to use an array.

counter=0;
arr=();

for ip in 172.16.10{0..4}.{0..255}; do
  counter=$((counter+1));
  arr[$counter]="$ip";
done

echo "${arr[500]}"

Output:

172.16.101.243

Your approach seems good enough to me. I would just print the result instead of defining a global variable that holds the result:

map_client_to_ipv4() {
    set "$(($1-1))"
    printf '%s\n' "172.16.10$(($1/256)).$(($1%256))"
}

map_client_to_ipv4 500
172.16.101.243

If you're using bash and you need to call map_client_to_ipv4 several times in your script then it might be advantageous to build an array that maps each client ID to its IP address, so that you can access the IPs directly:

#!/bin/bash

client_to_ipv4=( _ 172.16.10{0..4}.{0..255} )
unset client_to_ipv4[0] # remove the dummy first element

echo "${client_to_ipv4[500]}"
echo "${client_to_ipv4[800]}"
172.16.101.243
172.16.103.31

In any case, it's surely a good idea to do some validations on the client ID before using it:

map_client_to_ipv4() {
    case $1 in ( '' | 0* | *[^0-9]* ) return 1;; esac
    set "$(($1-1))"
    printf '%s\n' "172.16.10$(($1/256)).$(($1%256))"
}

map_client_to_ipv4 -0 || echo 'something went wrong' 1>&2
something went wrong
Related