Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy địa chỉ IP Client bằng JavaScript

Khái niệm

JavaScript chạy trên client (browser) không thể trực tiếp lấy IP của user do bảo mật. Cần gọi API bên ngoài trả về IP.

Cách phổ biến: JSONP / Fetch API

1. Dùng ipinfo.io (JSONP - cũ)

<!DOCTYPE html>
<html lang="vi">
<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', sans-serif; padding: 20px; text-align: center; }
        .result { font-size: 24px; font-weight: 500; color: #6a1b9a; margin: 30px 0; padding: 20px; background: #f3e5f5; border-radius: 8px; }
    </style>
</head>
<body>
    <h1>Lấy IP Client</h1>
    <div class="result" id="result">Đang lấy IP...</div>

    <script>
        const resEle = document.getElementById('result');

        // JSONP Callback
        window.showIP = (json) => {
            resEle.innerHTML = `IP công khai: ${json.ip}
Địa chỉ: ${json.city}, ${json.region}, ${json.country}
ISP: ${json.org}`; }; </script> <script src="https://ipinfo.io/?format=jsonp&callback=showIP"></script> </body> </html>

2. Dùng Fetch API (Hiện đại - Khuyến nghị)

<script>
async function getClientIP() {
    try {
        // ipapi.co - free tier 1000 req/day
        const response = await fetch('https://ipapi.co/json/');
        const data = await response.json();
        return data.ip;
    } catch (error) {
        console.error('Lỗi lấy IP:', error);
        return null;
    }
}

// Hoặc ipify.org
async function getIP() {
    const res = await fetch('https://api.ipify.org?format=json');
    const data = await res.json();
    return data.ip;
}

// Gọi
getClientIP().then(ip => console.log('IP:', ip));

3. Server-side (Backend) - Chính xác nhất

// Node.js/Express
app.get('/api/my-ip', (req, res) => {
    // X-Forwarded-For cho proxy/load balancer
    const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
    res.json({ ip });
});

// Client
fetch('/api/my-ip').then(r => r.json()).then(d => console.log(d.ip));

Lưu ý quan trọng

  • ⚠️ IP lấy được là Public IP (router/WAN), không phải Local IP (192.168.x.x)
  • User dùng VPN/Proxy → IP là của VPN/Proxy
  • CORS: API phải cho phép CORS hoặc dùng JSONP (cũ)
  • Rate limit: Free APIs thường giới hạn requests/ngày
  • Privacy: Cần thông báo user, tuân thủ GDPR

Các API miễn phí phổ biến

APIEndpointFormatRate Limit
ipapi.cohttps://ipapi.co/json/JSON1000/ngày
ipify.orghttps://api.ipify.org?format=jsonJSONKhông công khai
ipinfo.iohttps://ipinfo.io/jsonJSON50k/tháng (free)
ipwho.ishttps://ipwho.is/JSON10k/ngày

Kết quả ví dụ

IP công khai: 203.0.113.195
Địa chỉ: Hanoi, Hanoi, VN
ISP: Viettel Corporation