@pdz/portbinder

1.0.9 • Public • Published

Local TCP ports binding before use in sockets. Written in C and NAPI. Currently supports IPv4 only.

Example:

'use strict';

const portbinder = require('@pdz/portbinder');
const net = require('net');

let rsv;

try {
	rsv = portbinder.bind("8.8.8.8"); // Reserve port on 8.8.8.8 
} catch(e) {
	console.error('Port binding error:', e.message); // You not have premissions to 8.8.8.8 binding
}

try {
	rsv = portbinder.bind(""); // Reserve port on default IP
	console.log(rsv, 'Reserved');
} catch(e) {
	console.error(e); // No errors
}

const test = (rsv) => { // Test connection from reserved port
	const sock = new net.Socket()
	.once('connect', () => {
		console.log(rsv, 'Connected');
		sock.end().destroy();
	})
	.once('close', () => {
		console.log(rsv, 'Closed');
	})
	.once('error', (e) => {
		sock.end().destroy();
		console.error(rsv, 'Error:', e.code);
		// In first connect port is binded and connection fails with EADDRINUSE
		if(e.code == 'EADDRINUSE') {
			portbinder.unbind(rsv.fd); // Release binded port and try reconnect
			test(rsv); // Connection without errors
		}
	})
	.connect({
		host: 'example.com',
		port: 80,
		localAddress: rsv.ip,
		localPort: rsv.port
	});
}

test(rsv);

Result:

Port binding error: Cannot assign requested address
{ fd: 22, port: 58273, ip: '0.0.0.0' } Reserved
{ fd: 22, port: 58273, ip: '0.0.0.0' } Error: EADDRINUSE
{ fd: 22, port: 58273, ip: '0.0.0.0' } Closed
{ fd: 22, port: 58273, ip: '0.0.0.0' } Connected
{ fd: 22, port: 58273, ip: '0.0.0.0' } Closed

Readme

Keywords

Package Sidebar

Install

npm i @pdz/portbinder

Weekly Downloads

1

Version

1.0.9

License

ISC

Unpacked Size

75.6 kB

Total Files

15

Last publish

Collaborators

  • pdz