"use client"; import React, { useState, useEffect } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Network, Copy } from "lucide-react"; import { toast } from "sonner"; // --- Helper Functions --- // IPv4 const ipv4ToInt = (ip: string) => ip.split('.').reduce((acc, octet) => (acc << 8n) + BigInt(parseInt(octet, 10)), 0n); const intToIpv4 = (int: bigint) => [(int >> 24n) & 0xffn, (int >> 16n) & 0xffn, (int >> 8n) & 0xffn, int & 0xffn].join('.'); // IPv6 (simplified) const ipv6ToBigInt = (ip: string) => { // Expansion of :: if(ip.includes('::')) { const parts = ip.split('::'); const left = parts[0].split(':').filter(Boolean); const right = parts[1].split(':').filter(Boolean); const missing = 8 - (left.length + right.length); const expanded = [...left, ...Array(missing).fill('0'), ...right]; ip = expanded.join(':'); } const parts = ip.split(':'); let result = 0n; for (const part of parts) { result = (result << 16n) + BigInt(parseInt(part || '0', 16)); } return result; }; const bigIntToIpv6 = (int: bigint) => { let parts = []; for (let i = 0; i < 8; i++) { parts.unshift((int & 0xffffn).toString(16)); int >>= 16n; } // Simple compression (not full RFC 5952 compliant but good enough for display) return parts.join(':').replace(/(^|:)0(:0)*:0(:|$)/, '::'); }; export default function IpRadixPage() { const [ip, setIp] = useState("192.168.1.1"); const [type, setType] = useState<"IPv4" | "IPv6">("IPv4"); const [decimal, setDecimal] = useState(""); const [hex, setHex] = useState(""); const [binary, setBinary] = useState(""); const [errorV4, setErrorV4] = useState(""); const copyToClipboard = async (text: string) => { try { await navigator.clipboard.writeText(text); toast.success("已复制"); } catch { toast.error("复制失败"); } }; useEffect(() => { if (!ip.trim()) return; try { let val: bigint; if (ip.includes(':')) { setType("IPv6"); val = ipv6ToBigInt(ip); } else { setType("IPv4"); // Basic IPv4 validation if (!/^(\d{1,3}\.){3}\d{1,3}$/.test(ip)) { if (/^\d+$/.test(ip)) { // Treat as decimal input val = BigInt(ip); } else { throw new Error("Invalid Format"); } } else { val = ipv4ToInt(ip); } } setErrorV4(""); setDecimal(val.toString()); setHex("0x" + val.toString(16).toUpperCase()); setBinary(val.toString(2)); } catch { setDecimal("---"); setHex("---"); setBinary("---"); setErrorV4("无效的 IP 地址格式"); } }, [ip]); return (
IPv4/IPv6 地址与十进制、十六进制、二进制互转
{errorV4}
}自动识别 IPv4 / IPv6 格式。支持输入十进制整数反向转换。