node js incoming request sourceIP - node.js

For example:
http.createServer(function (request, response) {
request.on("end", function () {
});
});
Using Request, how I can I find the source IP of the request?

Depending on whether the request is made by a proxy forward or direct connection the source ip address may be stored at different places. You have to check req.header['x-forwarded-for'] first and then req.connection.remoteAddress. An example function is shown in this gist.

Here is a working example:
var http = require('http');
var getClientIp = function(req) {
var ipAddress = null;
var forwardedIpsStr = req.headers['x-forwarded-for'];
if (forwardedIpsStr) {
ipAddress = forwardedIpsStr[0];
}
if (!ipAddress) {
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};
var server = http.createServer();
server.on('request', function(req, res) {
console.log(getClientIp(req));
res.writeHead(200, {'Content-Type': 'text/plain'});
return res.end('Hello World\n');
});
server.listen(9000, 'localhost');
the getClientIp function was taken from here with some minor changes. Note that the contents of x-forwarded-for is an array containing proxy IPs, (read more here), so you may wish to inspect more than the first element.

Related

To parse the query string not working

Im self-educating Node.js. I have created two simple HTML files (summer.html and winter.html) and noded the JS on node.js. I went on localhost:5354/summer.html (and winter.html). Nothing is showing up and I got an error message
This site can’t be reached
The connection was reset.
Try:
Checking the connection
Checking the proxy and the firewall
Running Windows Network Diagnostics
ERR_CONNECTION_RESET
I have tested other lessons and was able to display results on localhost:5354/ but this one doesnt work. What did I do wrong?
JS
var http = require('http');
var url = require('url');
var fs = require('fs');
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(5343);
Hit this URL
localhost:5343/summer.html
Because, You listen in 5343 PORT. But you hit 5354 Port

Sending a single-packet HTTP response in Node.js

To show my students a simple HTTP request and response that they could capture using Wireshark, I whipped up a simple Node.js HTTP server:
var fs = require('fs');
var http = require('http');
var port = 80;
var file = process.argv[2]; //This file contains a 42 byte HTML page
http.createServer(function (req, res) {
res.writeHead(200, { 'content-type' : 'text/html' }); // Sends first packet
fs.createReadStream(file).pipe(res); // Sends second packet
}).listen(port);
Unfortunately, the two lines transmitting the HTTP header and the HTML are sent as two separate TCP packets (even though they are both quite small). It would be simpler for my students if the HTTP header and HTML were just one packet. How could I change my code to do this?
var http = require('http');
var fs = require('fs');
var file = process.argv[2];
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html;"});
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
response.write(html);
response.end();
});
}).listen(8000);
the reason it won't work is that Node.js runs everything asynchronously. When you are loading your html file, the server creation starts the same time. By the time you are about to write your html to your tcp socket, the file most likely won't be ready.
I see what you were trying to do before... I misread your code because of the indentation. Let me know if this snippet works.
try using something like-
var file = process.argv[2];
fs.readFile(file, function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});

NodeJS run server for receiving POST and serve GET

1) Running a NodeJS server on localmachine
2) One device with App making a POST req to Node server.
3) XAMPP page making a GET request to get what device (from point 2) sent to Node server.
hope that's clear.
this is what I have, but GET receives undefined.
POST logs key1=value1
var http = require('http');
http.createServer(function (req, res) {
console.log(req.method);
var txt;
if(req.method == "POST") {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
var url = require("url"),
parsedUrl = url.parse(req.url, false), // true to get query as object
queryAsObject = parsedUrl.query;
txt = JSON.stringify(queryAsObject);
console.log(txt);
} else {
// for GET requests, serve up the contents in 'index.html'
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello Worldzz\n'); // I WANT TO PASS txt here.
console.log("jaa" + txt);
}
}).listen(1337, 'my.ip.here');
console.log('Server running at http://my.ip.here:1337/');
-- update. CHECKing
function checkServer() {
$.ajax({
type: "GET",
url: "http://my.ip.here:1337/",
async: false,
}).success(function( text ) {
console.log("res" + text);
$( "h2" ).text( text );
});
}
This is just a simple scope problem. Since you want all requests to share the same txt var, you'll need to define txt in a place where all requests can access it.
var http = require('http');
var txt;
http.createServer(function (req, res) {
console.log(req.method);
//var txt;

How to get the port number in node.js when a request is processed?

If I have two node.js servers running, how can I tell which server called the processRequest function?
var http = require('http');
var https = require('https');
function processRequest(req, res) {
res.writeHead(200);
res.end("hello world, I'm on port: " + ???.port + "\n");
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);
Originally I wanted the port number, but couldn't find the object/variable to give it to me. Based on the below answer it makes more sense to determine encrypted vs non-encrypted since the point is to know which of the http servers the request came in on.
The req parameter is an instance of IncomingMessage from which you can access the socket.
From there you can access both the localPort and remotePort.
Something like:
console.log(req.socket.localPort);
console.log(req.socket.remotePort);
This way you get the port number:
var http = require('http');
var server = http.createServer().listen(8080);
server.on('request', function(req, res){
res.writeHead(200, {"Content-Type": "text/html; charset: UTF-8"});
res.write("Hello from Node! ");
res.write(" Server listening on port " + this.address().port);
res.end();
});
In case you are using http://localhost:<port_number>, then you can get the port number using req.headers.host property.
Example:
const http = require('http');
const server = http.createServer((req, res)=>{
console.log(req.headers.host); // localhost:8080
console.log(req.headers.host.split(':')[1]); // 8080
})
server.listen(8080);
Instead of checking port numbers, you can also check the server instance or the connection object:
var http = require('http'),
https = require('https');
function processRequest(req, res) {
var isSSL = (req.socket.encrypted ? true : false);
// alternate method:
// var isSSL = (this instanceof https.Server);
// or if you want to check against a specific server instance:
// var isServer1 = (this === server1);
res.writeHead(200);
res.end('hello world, i am' + (!isSSL ? ' not' : '') + ' encrypted!\n');
}
var server1 = http.createServer(processRequest).listen(80);
var server2 = https.createServer(processRequest).listen(443);

Get response from proxy server

I created a proxy server in node.js using the node-http-proxy module.
Looks like this:
var http = require('http'),
httpProxy = require('http-proxy'),
io = require("socket.io").listen(5555);
var proxy = new httpProxy.RoutingProxy();
http.createServer(function (req, res) {
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 1338
});
}).listen(9000);
So, I need, before sending the response back to the client to get the body from the server that I proxy and analyze it.
But I can't find event or attribute, where I can get this data. I tried:
proxy.on('end', function (data) {
console.log('end');
});
But I can't figure our how to get the mime body from it.
If all you want to do is examine the response (read-only) , you could use :
proxy.on('proxyRes', function(proxyRes, req, res){
proxyRes.on('data' , function(dataBuffer){
var data = dataBuffer.toString('utf8');
console.log("This is the data from target server : "+ data);
});
});
But , note that the 'proxyRes' event is emitted after the response is sent.
Reference in :
https://github.com/nodejitsu/node-http-proxy/issues/382
I found answer:
I rewrite response function for body -
var http = require('http'),
httpProxy = require('http-proxy'),
io = require("socket.io").listen(5555);
var proxy = new httpProxy.RoutingProxy();
http.createServer(function (req, res) {
console.log(req.url);
res.oldWrite = res.write;
res.write = function(data) {
/* add logic for your data here */
console.log(data.toString('UTF8'));
res.oldWrite(data);
}
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 1338
});
}).listen(9000);
This code will console all url request and response form this endpoint.
Based on the answer of #Psycho, following code can be used to modify headers as well
var server = http.createServer(function(req, res) {
res.oldWrite = res.write;
res.write = function(data) {
console.log(data.toString('UTF8'));
res.oldWrite(data);
}
res.oldSetHeader = res.setHeader
res.setHeader = function(k,v) {
console.log(k,v)
res.oldSetHeader(k,v)
}
proxy.web(req, res, { target: proxyPool[key]}); })

Resources