Home > database >  How to map a client ID to an IPv4 address?
How to map a client ID to an IPv4 address?

Time:08-08

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%6))
  ret_val=172.16.10${val}.$((mod-1))
}

map_client_to_ipv4 500
echo $ret_val

CodePudding user response:

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

CodePudding user response:

I would use a global bash array that will map each client ID to its IP address, so that you can access the IPs:

  • in a simple way:
#!/bin/bash

client_to_ipv4=( _ 172.16.10{0..4}.{0..255} )
unset client_to_ipv4[0]
echo "${client_to_ipv4[500]}"
172.16.101.243
  • or with a function that validates the arguments:
#!/bin/bash

IPs=( _ 172.16.10{0..4}.{0..255} )
unset IPs[0]

map_client_to_ipv4() {
    local rc=0 client_id
    for client_id
    do
        if [[ $client_id =~ ^[0-9] $ ]] && [[ ${IPs[client_id] 1} ]]
        then
            echo "${IPs[client_id]}"
        else
            printf 'error: invalid ID: %q\n' "$client_id" 1>&2
            (( rc   ))
        fi
    done
    return "$rc"
}
map_client_to_ipv4 500 800 'foo bar' 0 99999
172.16.101.243
172.16.103.31
error: invalid ID: foo\ bar
error: invalid ID: 0
error: invalid ID: 99999

echo "$?"
3
  •  Tags:  
  • bash
  • Related