Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ดึง IP Address ของ Client ด้วย JavaScript

JavaScript ฝั่ง Client (Browser) ไม่สามารถอ่าน IP Address ได้โดยตรง เพราะเหตุผลด้านความปลอดภัยและความเป็นส่วนตัว ต้องใช้ External Service (Third-party API) ที่คืนค่า IP กลับมาในรูปแบบ JSONP หรือ CORS

ตัวอย่าง: ใช้ ipinfo.io API (JSONP)

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Client IP</title>
    <style>
        body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; text-align: center; }
        .result { font-size: 24px; font-weight: 500; color: blueviolet; margin: 20px 0; }
    </style>
</head>
<body>
    <h1>ดึง IP Address ของ Client</h1>
    <div class="result" id="result">กำลังดึง IP...</div>

    <script>
        const result = document.getElementById("result");
        
        // Callback Function สำหรับ JSONP
        window.showIP = function(json) {
            result.innerHTML = `🌐 IP สาธารณะของคุณ: ${json.ip}
📍 ประเทศ: ${json.country}
🏙️ เมือง: ${json.city}
🌐 ISP: ${json.org}`; }; </script> <!-- JSONP Callback: showIP --> <script src="https://ipinfo.io/?format=jsonp&callback=showIP"></script> </body> </html>

ผลลัพธ์

แสดง IP Address, ประเทศ, เมือง, และ ISP ของผู้ใช้งาน

วิธีการทำงาน (JSONP)

  1. สร้าง Global Function showIP(json)
  2. โหลด Script จาก https://ipinfo.io/?format=jsonp&callback=showIP
  3. Server ส่งคืน: showIP({"ip":"1.2.3.4","country":"TH",...})
  4. Browser เรียก showIP ด้วยข้อมูล JSON

วิธี Modern: Fetch API + CORS (แนะนำ)

<script>
async function getClientIP() {
    try {
        // ใช้ API ที่รองรับ CORS
        const response = await fetch("https://api.ipify.org?format=json");
        const data = await response.json();
        return data.ip;
    } catch (error) {
        console.error("Failed to get IP:", error);
        return null;
    }
}

// ใช้งาน
getClientIP().then(ip => {
    if (ip) console.log("Your IP:", ip);
});
</script>

API ฟรีที่นิยมใช้ (Free IP APIs)

APIEndpointFormatRate Limit
ipifyhttps://api.ipify.org?format=jsonJSON (CORS)1,000 req/day
ipinfo.iohttps://ipinfo.io/jsonJSON (CORS)50,000 req/month
ipapi.cohttps://ipapi.co/json/JSON (CORS)1,000 req/day
ipwho.ishttps://ipwho.is/JSON (CORS)10,000 req/month
cloudflarehttps://cloudflare.com/cdn-cgi/tracePlain TextUnlimited

⚠️ ข้อควรระวังและข้อจำกัด

  • ไม่ได้ IP จริงถ้าผ่าน Proxy/VPN/CDN - จะได้ IP ของ Proxy/Edge Server
  • Rate Limits - API ฟรีมีข้อจำกัด จัดการ Cache/Error Handling ให้ดี
  • Privacy/GDPR - IP เป็น Personal Data ต้องได้รับความยินยอมก่อนเก็บ
  • CORS - ต้องใช้ API ที่รองรับ CORS หรือ JSONP (Legacy)
  • HTTPS Required - Modern Browsers บล็อก Mixed Content (HTTP บน HTTPS Site)

ทางเลือก: Server-side IP Detection

// Node.js (Express)
app.get("/api/client-ip", (req, res) => {
    // Trust Proxy Header (ถ้าอยู่หลัง Load Balancer/Proxy)
    const ip = req.headers["x-forwarded-for"]?.split(",")[0]?.trim() 
            || req.headers["x-real-ip"] 
            || req.socket.remoteAddress;
    res.json({ ip });
});

// Frontend
fetch("/api/client-ip").then(r => r.json()).then(data => console.log(data.ip));

วิธีนี้น่าเชื่อถือกว่า เพราะ Server เห็น IP จริงของ Connection

สรุป

  • Client-side JS ไม่เข้าถึง IP ได้โดยตรง
  • ใช้ External API (ipify, ipinfo, etc.) ผ่าน Fetch/JSONP
  • แนะนำ: ใช้ Backend API ของตัวเอง (น่าเชื่อถือ, ควบคุมได้, ปลอดภัย)
  • จัดการ Error, Loading State, และ Rate Limits ให้เหมาะสม