nodejs v5.10.1 cannot get my host address anymore? - linux

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;
}
}
}

Related

Run same Node.js App on IPV4 and IPV6 simultaneously?

I know when I have the hostname as "::" this means the same as "0.0.0.0" in IPV4.
const express = require('express')
const app = express()
const port =80
const host6 = "::";
const host4 = "0.0.0.0";
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, host6, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
This App should now be accessible through IPV6 but als IPV4. But devices which don't understand IPV6 can not make the initial request over IPV6, so for them the App is not accessible.
How can I run this App on both IP versions on the same Port 80?
Unconfirmed, but I would try to remove the host from the arguments passed to app.listen and only pass the port, app.listen(port).
Express docs for app.listen state that
This method is identical to Node’s http.Server.listen().
Node's documentation for http.Server.listen state that
This method is identical to server.listen() from net.Server.
Node's documentation for net.Server states that
If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.

Socketio not connecting on postman socket connection ui on localhost

Could not connect to localhost:3000
17:02:53
Error: Unexpected server response: 404
Handshake Details
Request URL: http://localhost:3000/socket.io/?EIO=3&transport=websocket
Request Method: GET
Status Code: 404 Not Found
My express server listen on 3000 port and socketio http on 443 port, i am able to connect socket by hosting this on ec2 instance and using ec2 ip with port number on postman socket connection ui, but on localhost connection always failed with above error on postman socket beta ui.
You need to call listen only once. If you pass your http/https server to express, app.listen() is enough. (except you want to listen on 2 different ports.. For testing, let's call it only once.)
For accessing it on localhost try setting it explicitly with the parameter hostname in app.listen().
Example:
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
// Let's only call listen once for testing purposes. If you call
// listen on the express app, your https server will automatically listen
// to the same configuration.
// httpsServer.listen(4000);
const port = 3000
const hostname = 'localhost'
// explicitly let the app listen on localhost. If hostname is not
// provided, it will take the first found ipv4 interface
app.listen(port, hostname, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on https://${hostname}:${port} 🛡️
################################################
`);
});
}
Now you should be able to connect your socket. If it still does not work try
to use http module instead of https for better isolating your problem.
Note that your server now only will be accessible using localhost and not over ip. Both may only be possible when running 2 server instances with different hostnames.
async function startServer() {
const app = express();
const credentials = {key: key, cert: crt};
const httpsServer = createServer(credentials,app);
const io = socketIO(httpsServer);
await require('./loaders').default({ expressApp: app, socketIO: io });
httpsServer.listen(443);
app.listen(config.port, err => {
if (err) {
Logger.error(err);
process.exit(1);
return;
}
Logger.info(`
################################################
🛡️ Server listening on port: ${config.port} 🛡️
################################################
`);
});
}
This is my app.ts file, I am using Ubuntu. so 443 port is not allowed, i changed this port to 4000, now the app listen on the 3000 and socket http server on 4000, but socketio not able to connect with socket url localhost:3000

Why it's create localhost:5000 CLOSE_WAIT Node?

my server started with PORT 5000, and sometimes it show next error
Error: listen EADDRINUSE: address already in use :::5000
When I Check port 5000, I see what port :5000 use for Chrome. They pass away after time( 1 min ) but, it's create more problems, i don't check code with terminal, because after error not showing console.log?
I think that chrome is launched by some development tool. Because System apps can not take port number more that 1024. So you need to check if your IDE is launching it and then check how to change the port or you can follow this link to auto increment the port if given port is not available.
var portrange = 45032
function getPort (cb) {
var port = portrange
portrange += 1
var server = net.createServer()
server.listen(port, function (err) {
server.once('close', function () {
cb(port)
})
server.close()
})
server.on('error', function (err) {
getPort(cb)
})
}
Code from link

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);
});

bind udp server to external ip via port forwarding

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?

Resources