Reputation: 991
I want to get user client's IP address. This is my code:
const server = http2.createSecureServer({
key: fs.readFileSync('localhost.key'),
cert: fs.readFileSync('localhost.crt')
});
server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
console.log('Path:' + headers[':path']);
console.log('User Agent:' + headers['user-agent']);
console.log('Cookie:' + headers.cookie);
stream.respond({
'content-type': 'text/html',
':status': 200
});
stream.end('<h1>Hello World</h1>');
});
I have already read the node.js documentation. There I found this example:
const http2 = require('http2');
const server = http2.createServer((req, res) => {
const ip = req.socket.remoteAddress;
const port = req.socket.remotePort;
res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);
But they don't use the stream object. So my question is, how can I get the client's IP address with my code at the very top of this post?
Upvotes: 1
Views: 535
Reputation: 21
You can try const ip = stream.session.socket.remoteAddress
It's not easy to find in documentation, but it works for me ;)
http2session_and_sockets in docs find the "http2session.socket" chapter
Upvotes: 2