I have created a ws websocket server in nodejs and a http server that is listening on a specific port and host is 127.0.0.1. WebSocket server connection is established on the upgrade event emitted by the http server. For security purpose I want the server to be accessible only on localhost/127.0.0.1 and not from 0.0.0.0 IP.
Example:
- ws://0.0.0.0:5050 - Should not accept connections
- ws://127.0.0.1:5050 - Should accept connections
How can I restrict the server to be only reachable from localhost and not from any other IP(including 0.0.0.0)?
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
server.listen(5050, '127.0.0.1');
server.on('upgrade', function (request, socket, head) {
wss.handleUpgrade(request, socket, head, function (ws) {
//conditional checks
wss.emit('connection', ws, request);
})
})
Can somebody please direct me to the proper way of doing this.