0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CIDR形式アドレスを個別IPに展開

Last updated at Posted at 2025-03-04
#!/bin/sh

# 入力ファイルと出力ファイル
INPUT_FILE="iprange_place.csv"
OUTPUT_FILE="ip_place.csv"

# 出力ファイルのヘッダーを生成
echo "IP,Place" > "$OUTPUT_FILE"

# 入力ファイルを1行ずつ処理 (ヘッダー行をスキップ)
tail -n +2 "$INPUT_FILE" | while IFS=, read -r ip_range place; do
  # IPレンジをCIDR形式で分割
  ip_prefix=$(echo "$ip_range" | cut -d '/' -f 1)
  cidr_mask=$(echo "$ip_range" | cut -d '/' -f 2)

  # IPプレフィックスを数値に変換
  IFS=. read -r octet1 octet2 octet3 octet4 <<< "$ip_prefix"
  ip_num=$(( (octet1 * 256 * 256 * 256) + (octet2 * 256 * 256) + (octet3 * 256) + octet4 ))

  # CIDRマスクからIPアドレスの範囲を計算
  mask=$(( (0xffffffff << (32 - cidr_mask)) & 0xffffffff ))
  network_address=$(( ip_num & mask ))
  broadcast_address=$(( network_address + (2**(32 - cidr_mask)) - 1 ))

  # IPアドレスを生成して出力
  for ((i=network_address; i<=broadcast_address; i++)); do
    octet1=$(( (i >> 24) & 255 ))
    octet2=$(( (i >> 16) & 255 ))
    octet3=$(( (i >> 8) & 255 ))
    octet4=$(( i & 255 ))
    ip=$(printf "%d.%d.%d.%d" "$octet1" "$octet2" "$octet3" "$octet4")
    echo "$ip,$place" >> "$OUTPUT_FILE"
  done
done

echo "IPアドレスと場所の対応ファイル ($OUTPUT_FILE) が生成されました。"
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?