Skip to content

Instantly share code, notes, and snippets.

@femto113
Created January 23, 2014 08:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save femto113/8574732 to your computer and use it in GitHub Desktop.
Save femto113/8574732 to your computer and use it in GitHub Desktop.
canonical web service port numbering scheme. See blog post for details: http://www.codesuck.com/2014/01/a-simple-canonical-port-numbering.html
// given a service name return a canonical TCP port number in the range of 1024 - 33791
function port(serviceName)
{
// replace any invalid digits with valid ones
serviceName = serviceName.replace(/[^A-Va-v0-9]/g, mapSpecialChar);
// take the first 3 characters (= first 15 bits), right padding with 0 as necessary
serviceName = (serviceName + '00').substring(0, 3);
// interpret as 15-bit, base32 encoded int,
// then add 1024 to clear the restricted ports
return parseInt(serviceName, 32) + 1024;
}
function mapSpecialChar(c)
{
// find the closest (in ASCII space), valid, base-32 digit
return ['0','9','A','V','a','v'].map(function (v) {
return [ Math.abs(v.charCodeAt(0) - c.charCodeAt(0)), v ];
}).sort(function (a, b) {
return a[0] - b[0];
})[0][1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment