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)
- สร้าง Global Function
showIP(json) - โหลด Script จาก
https://ipinfo.io/?format=jsonp&callback=showIP - Server ส่งคืน:
showIP({"ip":"1.2.3.4","country":"TH",...}) - 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)
| API | Endpoint | Format | Rate Limit |
|---|---|---|---|
| ipify | https://api.ipify.org?format=json | JSON (CORS) | 1,000 req/day |
| ipinfo.io | https://ipinfo.io/json | JSON (CORS) | 50,000 req/month |
| ipapi.co | https://ipapi.co/json/ | JSON (CORS) | 1,000 req/day |
| ipwho.is | https://ipwho.is/ | JSON (CORS) | 10,000 req/month |
| cloudflare | https://cloudflare.com/cdn-cgi/trace | Plain Text | Unlimited |
⚠️ ข้อควรระวังและข้อจำกัด
- ไม่ได้ 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 ให้เหมาะสม