如何获取访客IP地址并写入文件

获取访客IP地址在很多应用场景中都很有用,比如网站分析、用户行为追踪等。本文将介绍两种方法来获取访客IP地址并将其写入文件。

方法一:使用JavaScript获取IP地址并显示

您可以使用JavaScript调用IPify API来获取访客的IP地址,并将其显示在网页上。

// 使用JavaScript获取IP地址
fetch('https://api.ipify.org?format=json')
    .then(response => response.json())
    .then(data => {
        const ipAddress = data.ip;
        const p = document.createElement('ip');
        p.textContent = ipAddress;
        document.body.appendChild(p);
    })
    .catch(error => {
        console.error('获取IP地址时发生错误:', error);
    });

方法二:使用Node.js编写服务器端脚本获取IP地址并写入文件

由于JavaScript在浏览器中无法直接访问本地文件系统,因此无法将获取的IP地址直接写入1.txt文件。如果您想要将获取的IP地址写入文件,需要使用一些服务器端的技术来实现。您可以使用Node.js编写一个简单的服务器端脚本,将获取的IP地址写入1.txt文件中。

以下是一个简单的Node.js脚本示例:

const http = require('http');
const fs = require('fs');

http.createServer((req, res) => {
    if (req.url === '/getIP') {
        // 使用JavaScript获取IP地址
        fetch('https://api.ipify.org?format=json')
            .then(response => response.json())
            .then(data => {
                const ipAddress = data.ip;
                // 将IP地址写入文件
                fs.writeFile('1.txt', ipAddress, (err) => {
                    if (err) {
                        console.error('写入文件时发生错误:', err);
                        res.writeHead(500);
                        res.end('写入文件时发生错误');
                    } else {
                        res.writeHead(200);
                        res.end('IP地址已写入文件');
                    }
                });
            })
            .catch(error => {
                console.error('获取IP地址时发生错误:', error);
                res.writeHead(500);
                res.end('获取IP地址时发生错误');
            });
    } else {
        res.writeHead(404);
        res.end('请求的页面不存在');
    }
}).listen(8080, () => {
    console.log('服务器已启动,监听端口8080');
});

您可以将上述代码保存为一个文件(例如server.js),然后在终端中运行以下命令启动服务器:

node server.js

然后在浏览器中访问http://localhost:8080/getIP,服务器将会获取访问者的IP地址并将其写入1.txt文件中。如果写入成功,浏览器将会显示"IP地址已写入文件"。如果发生错误,浏览器将会显示相应的错误信息。

如何获取访客IP地址并写入文件

原文地址: https://www.cveoy.top/t/topic/n9CQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录