IPアドレスを扱うプログラミング・サンプル集
各言語での「IP検証」「CIDR判定」「整数変換」の基本パターンをまとめます。
Go
package main
import (
"fmt"
"net"
"net/netip"
)
func main() {
// 検証
ip := net.ParseIP("192.168.0.10")
fmt.Println(ip != nil) // true
// CIDR判定
_, cidr, _ := net.ParseCIDR("192.168.0.0/24")
fmt.Println(cidr.Contains(ip)) // true
// 整数化(netip)
a, _ := netip.ParseAddr("192.168.0.10")
fmt.Printf("%x\n", a.As4()) // c0a8000a
}
Python
import ipaddress
ip = ipaddress.ip_address("192.168.0.10")
net = ipaddress.ip_network("192.168.0.0/24")
print(ip in net) # True
print(int(ip)) # 3232235530
print(ip.version) # 4
print(net.num_addresses)# 256
JavaScript (Node.js)
import net from "node:net";
console.log(net.isIP("192.168.0.10")); // 4
console.log(net.isIP("::1")); // 6
// 整数化
const toInt = ip =>
ip.split(".").reduce((a, o) => (a << 8 >>> 0) + Number(o), 0) >>> 0;
console.log(toInt("192.168.0.10")); // 3232235530
PHP
<?php
var_dump(filter_var("192.168.0.10", FILTER_VALIDATE_IP) !== false); // true
echo ip2long("192.168.0.10"); // 3232235530
echo long2ip(3232235530); // 192.168.0.10
C
#include <stdio.h>
#include <arpa/inet.h>
int main(void) {
struct in_addr a;
if (inet_pton(AF_INET, "192.168.0.10", &a) == 1) {
printf("network-order hex: %08x\n", a.s_addr);
}
return 0;
}
クライアントから自IPを取得(fetch)
const { ip } = await fetch("https://show-ip-addr.com/api/myip").then(r => r.json());
console.log(ip);
CIDRの手計算が面倒なときは サブネット計算機、進数変換は IP変換ツール も活用してください。