
我们可以创建一个返回 Promise 的函数来获取 IP 地址:
function getIPAddress() {
return new Promise((resolve, reject) => {
// 发送异步请求获取 IP 地址
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => resolve(data.ip))
.catch(error => reject(error));
});
}
在需要获取 IP 地址的地方使用 Promise:
getIPAddress()
.then(ipAddress => {
console.log('IP Address:', ipAddress);
})
.catch(error => {
console.error('Error getting IP address:', error);
});
使用 async/await 语法可以让代码看起来更加清晰:
async function getIPAddress() {
try {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
return data.ip;
} catch (error) {
throw error;
}
}
async function displayIPAddress() {
try {
const ipAddress = await getIPAddress();
console.log('IP Address:', ipAddress);
} catch (error) {
console.error('Error getting IP address:', error);
}
}
displayIPAddress();
在 Node.js 应用程序中,我们可以通过 req.connection.remoteAddress 或 req.socket.remoteAddress 属性来获取客户端的 IP 地址。例如:
const http = require('http');
const server = http.createServer((req, res) => {
const clientIPAddress = req.connection.remoteAddress || req.socket.remoteAddress;
console.log('Client IP Address:', clientIPAddress);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});