我们有3座建筑物,我想使用一系列if / else语句来确定计算机拥有的IP,然后确定它在哪个子网中。
例如:
我想我已经找到了如何识别计算机IP的方法,现在我只需要一点帮助就可以确定如何将IP地址更改为可以评估的数字。到目前为止,这是我所拥有的,但是我不知道如何以某种方式转换IP。
#!/bin/bash
ip=192.168.1.20
building1min=192.168.1.1
building1max=192.168.1.255
building2min=192.168.2.1
building2max=192.168.2.255
building3min=192.168.3.1
building3max=192.168.3.255
if [ $ip -lt $building1max && $ip -gt $building1min ]{
echo "User is in Building 1"
} else if [ $ip -lt $building2max && $ip -gt $building2min ]
echo "User is in Building 2"
} else if [ $ip -lt $building3max && $ip -gt $building3min ]{
echo "User is in Building 3"
} else {
echo "User is not in any building"
}
答案 0 :(得分:0)
以下代码应为您指明正确的方向:
#!/usr/bin/env bash
binary=( {0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1} )
convertToBinary() {
local -a oct
local o res ip=$1 mask=$2
IFS=. read -ra oct <<< "$ip"
for o in "${oct[@]}"; do
res+=${binary[o]}
done
printf '%s\n' "${res:0:mask}"
}
isInSubnet() {
local sub=$1 ip=$2
local sub_ip=${sub%/*} sub_mask=${sub#*/}
[[ $(convertToBinary "$sub_ip" "$sub_mask") = "$(convertToBinary "$ip" "$sub_mask")" ]]
}
# USAGE
ip=192.168.2.15
b1=192.168.1.0/24 b2=192.168.2.0/24
if isInSubnet "$b1" "$ip"; then
echo building 1
elif isInSubnet "$b2" "$ip"; then
echo building 2
fi
它首先将IP转换为二进制,然后仅提取网络地址,然后检查是否相等。