bind udp server to external ip via port forwarding - node.js

Is it possible to connect a udp socket to an external ip after port forwarding is done?
var PORT = 33333;
var HOST = 'xxx.xx.xxx.xxx'; // my external ip
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" +
address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port +' - ' +
message);
});
server.bind(PORT, HOST);
port forwarding already set up (below)
I'm getting 'EADDRNOTAVAIL' error
Error: bind EADDRNOTAVAIL xxx.xx.xxx.xxx:33333
Is this even possible? and if not, what are my options for listening in to remote ip addresses?
Thank
Asaf

You can't bind to a non-local address, and you don't need to. Just bind to 0.0.0.0. The port forwarding will do the rest.

Could you use var HOST = '0.0.0.0'; for connecting outside your host?

Related

Nodejs doesn't redirect to https

I have a node server with express on top. Godaddy is the domain registrar that I use.
If I try to connect with www.example.com doesn't work, only with https://www.example.com.
This is how the code looks like:
app.use(express_enforces_ssl());
app.enable('trust proxy');
app.use (function (req, res, next) {
if(req.secure){
next();
}else {
res.redirect('https://' + req.headers.host + req.url);
}
});
var options = {
ca: fs.readFileSync('./gd_bundle-g2-g1.crt'),
key: fs.readFileSync('./server_cert_key.key'),
cert: fs.readFileSync('./cfbe0f99da37dcae.crt')
};
https = require('https').createServer(options, app);
io = require('socket.io')(https);
However, if I 'ping www.example.com' the server is reached, but not in the browser.
The process is running on port 443 (dedicated port for secured connection).
I have made port forwarding from internal port 443 with output on port 80, this is how domain registrar works, only with port 80.
I don't know how can I fix it. Do you have any idea ?
DNS doesn't usually require ports info. Browser automatically assumes 80 for http scheme and 443 for https scheme.
The app code is only listening on 443. You need to add additional:
require('http').createServer(app).listen(80);
Try normalizing the port before listen to it.
In the code below, the port will be normalized according to the app settings. If none were found, it will be defaulted to port 80
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) return val;
if (port >= 0) return port;
return false;
}
//port 443 if https:// is detected
var port = normalizePort(process.env.PORT || '80');
// for me, I imported ('http') instead of ('https')
// but it also works on port 443
https.listen(port, function listening() {
console.log('Listening on %d', server.address().port);
});

Https server with socket and express

I'm using SSL to encrypt my backend but my current solution opens two ports, one for sockets and the other for express, any approach to start both on the same port like HTTP ?
const port=4000;
if(process.env.ENABLE_SSL=='true')
{
////two ports are open 8989,4000
server = https.createServer({
key: fs.readFileSync("sslLocation/ssl.key"),
cert: fs.readFileSync("sslLocation/ssl.cert")
},app).listen("8989", '0.0.0.0',function(){
console.log('Express server listening to port 8989');
});
global.io = require('socket.io').listen(server);
app.listen(port);
}
else
{
////one port only
// start the server
server = app.listen(port, function () {
console.log(`App is running at: localhost:${server.address().port}`);
});
global.io = require('socket.io').listen(server);
}
also running app.listen(server) in the ssl section, i can't access the apis

nodejs v5.10.1 cannot get my host address anymore?

Why the latest version of nodejs (v5.10.1) cannot get my host address anymore?
express code:
var express = require('express');
var app = express();
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log(server.address());
console.log('Example app listening at http://%s:%s', host, port);
});
result:
{ address: '::', family: 'IPv6', port: 3000 }
Example app listening at http://:::3000
It should be:
http://127.0.0.1
Any ideas how I can fix this?
I am on Linux.
Actually, maybe you will see something like
:80
and then
::80
actually this one have a pattern like this:
host:port IPv4
host::port IPv6
127.0.0.1:80 means that using IPv4, listening in 127.0.0.1 in port 80
:80 means that using IPv4 ,listening on all address in port 80
127.0.0.1::80 means that using IPv6, listening in 127.0.0.1 in port 80
and so on.
so, the ::3000 means listening to IPv6 in port 3000
These configuration was done under these variable
var host = server.address().address;
var port = server.address().port;
you can just change the value of these variable to "127.0.0.1" and "80" and see what happens, but most likely your machine still using IPv6 there, if you want to change to IPv4 for your machine, change the setting of your machine under:
Windows: control panel -> network and sharing center -> (your network) -> properties -> setup the IPv4
Linux: i dont have linux machine to test this, but the syntax should be using ifconfig or ipconfig depends on your linux, please refer for something like https://unix.stackexchange.com/questions/34093/static-ipv4-ipv6-configuration-on-centos-6-2
Mac: i dont have mac machine also, should be the same with linux so try to do the same also
I have the same problem, i solved it acessing like an array:
server.address()["port"]
Here a example:
export const onError = (server: Server) => {
console.log(server.address()["port"])
return (error: NodeJS.ErrnoException): void => {
let port: number | string = server.address()["port"];
if (error.syscall !== 'listen') throw error;
let bind = (typeof port === 'string') ? `pipe ${port}` : `port ${port}`;
switch(error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
}
}

Openshift port for node.js

I have a server that won't start correctly on openshift. This is my code:
var connect = require("connect");
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var httpServer = connect.createServer(connect.static(__dirname + "/public")).listen(port);
console.log("Listening on " + port + "...");
I keep getting this error:
info: socket.io started
warn: error raised: Error: listen EACCES
DEBUG: Program node server.js exited with code 0
DEBUG: Starting child process with 'node server.js'
Listening on 8080...
How can I solve this?
You need to bind the listening IP address to process.env.OPENSHIFT_NODEJS_IP. Here is the example from my working code (I'm using Express) on OpenShift.
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.listen(port, ipaddress, function() {
// Do your stuff
});
We need to specify the binding to your OPENSHIFT_NODEJS_IP in your listen like:
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1"; (do not forget quotes)
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;

Changing Node.js listening port

I just installed node.js on Windows. I have this simple code which does not run:
I get:
Error: listen EADDRINUSE
Is there a config file that tells node.js to listen on a specific port?
The problem is I have Apache listening on port 80 already.
EDIT:
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
console.log("Request: " + req.method + " to " + req.url);
res.writeHead(200, "OK");
res.write("<h1>Hello</h1>Node.js is working");
res.end();
}).listen(5454);
console.log("Ready on port 5454");
There is no config file unless you create one yourself. However, the port is a parameter of the listen() function. For example, to listen on port 8124:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
If you're having problems finding a port that's open, you can go to the command line and type:
netstat -ano
To see a list of all ports in use per adapter.
I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080 to your console.
you can get the nodejs configuration from http://nodejs.org/
The important thing you need to keep in your mind is about its configuration in file app.js which consists of port number host and other settings these are settings working for me
backendSettings = {
"scheme":"https / http ",
"host":"Your website url",
"port":49165, //port number
'sslKeyPath': 'Path for key',
'sslCertPath': 'path for SSL certificate',
'sslCAPath': '',
"resource":"/socket.io",
"baseAuthPath": '/nodejs/',
"publishUrl":"publish",
"serviceKey":"",
"backend":{
"port":443,
"scheme": 'https / http', //whatever is your website scheme
"host":"host name",
"messagePath":"/nodejs/message/"},
"clientsCanWriteToChannels":false,
"clientsCanWriteToClients":false,
"extensions":"",
"debug":false,
"addUserToChannelUrl": 'user/channel/add/:channel/:uid',
"publishMessageToContentChannelUrl": 'content/token/message',
"transports":["websocket",
"flashsocket",
"htmlfile",
"xhr-polling",
"jsonp-polling"],
"jsMinification":true,
"jsEtag":true,
"logLevel":1};
In this if you are getting "Error: listen EADDRINUSE" then please change the port number i.e, here I am using "49165" so you can use other port such as 49170 or some other port.
For this you can refer to the following article
http://www.a2hosting.com/kb/installable-applications/manual-installations/installing-node-js-on-shared-hosting-accounts

Resources