I have following sample code
used in the tcp server
var server = net.createServer();
server.on('connection', function (socket) {
if(restrictedIP == sock.remoteAddress){
//How to close the particular connection safely without
//affecting other connections
}
socket.on('data', function(data) {
console.log(data);
});
socket.on('close', function(data) {
console.log('client disconnected');
});
});
server.listen(3000, '127.0.0.1');
Note : I have a check to authenticate the client/server ip (3rd line).
Problem :
Whether this logic sounds good to authenticate the client/server.
Main thing, How to close the particular connection from the restricted ip address.(4th line - comment)
Scenario :
I have two servers one is client server which is express/http server lets name it as server1-express
, and other one is tcp server named as server2-tcp
.
server1-express
server will talk toserver2-tcp
using tcp.server2-tcp
should only allow this particularserver1-express
server, It shouldn't allow connection to any other ip,Using socket.destroy() will crash the
server2-tcp
.Using socket.end() will force us to
write
to servers.
How to allow only particular ip
and deny all other ip
access?
Any help or suggestion will be grateful
It depends on what you mean by "authenticate", but obviously an IP address could be used by multiple people (e.g. behind a router). So if that is a concern, you will have to come up with your own protocol or re-use an existing one (probably a better idea to use one that has been "battle tested"). A more "complex" example would be to use TLS, which is built into node and would give you both encryption and authentication via certificates/keys, while still giving you a raw socket.
As far as terminating a connection goes, you can do that gracefully by calling
.end()
on the socket, or.destroy()
to forcefully terminate the socket.