Stories

Detail Return Return

如何使用 Shell 腳本驗證 IPv4 地址 ? - Stories Detail

# How to Validate IPv4 Addresses in Shell Script

驗證 IP 地址是網絡和系統管理中的一項常見任務。在本教程中,我們將學習如何使用 shell 腳本驗證 IPv4 地址。這在需要確保用户輸入或來自其他來源的數據採用正確的 IPv4 格式的情況下特別有用。

IPv4 地址格式

IPv4 地址由 4 個 8 字節組成,每個 8 字節的取值範圍為 0 ~ 255,中間用點分隔。例如:192.168.1.1 是合法的 IPv4 地址。

編寫腳本

我們將使用一個函數來驗證 IPv4 地址,該函數使用正則表達式檢查輸入是否與 IPv4 模式匹配。

#!/bin/bash
# Filename: validate_ip.sh

validate_ip() {
    local ip=$1
    local stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi

    return $stat
}

echo -n "Enter IPv4 address: "
read ip_address

if validate_ip $ip_address; then
    echo "${ip_address} is a valid IPv4 address."
else
    echo "${ip_address} is a invalid IPv4 address."
fi

測試腳本

(1) 讓腳本可執行: chmod +x validate_ip.sh

(2) 運行腳本: ./validate_ip.sh

(3) 根據提示輸入 IPv4 地址

我的開源項目

酷瓜雲課堂-在線教育解決方案

  • course-tencent-cloud(酷瓜雲課堂 - gitee倉庫)
  • course-tencent-cloud(酷瓜雲課堂 - github倉庫)
user avatar joyssl Avatar
Favorites 1 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.