簡體   English   中英

查找IP地址並驗證它在哪個子網中

[英]Find IP address and validate which subnet it is in

我們有3座建築物,我想使用一系列if / else語句確定計算機擁有的IP,然后確定它在哪個子網中。

例如:

  • 1號樓= 192.168.1.1 / 24
  • 2號樓= 192.168.2.1 / 24
  • 3號樓= 192.168.3.1 / 24

我想我已經找到了如何識別計算機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"
}

以下代碼應為您指明正確的方向:

#!/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轉換為二進制,然后僅提取網絡地址,然后檢查是否相等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM