@@ -834,6 +834,15 @@ function connect(self, address, port, addressType, localAddress, localPort) {
834834}
835835
836836
837+ // Check that the port number is not NaN when coerced to a number,
838+ // is an integer and that it falls within the legal range of port numbers.
839+ function isLegalPort ( port ) {
840+ if ( typeof port === 'string' && port . trim ( ) === '' )
841+ return false ;
842+ return + port === ( port >>> 0 ) && port >= 0 && port <= 0xFFFF ;
843+ }
844+
845+
837846Socket . prototype . connect = function ( options , cb ) {
838847 if ( this . write !== Socket . prototype . write )
839848 this . write = Socket . prototype . write ;
@@ -896,16 +905,14 @@ Socket.prototype.connect = function(options, cb) {
896905 if ( localPort && typeof localPort !== 'number' )
897906 throw new TypeError ( 'localPort should be a number: ' + localPort ) ;
898907
899- if ( typeof options . port === 'number' )
900- port = options . port ;
901- else if ( typeof options . port === 'string' )
902- port = options . port . trim ( ) === '' ? - 1 : + options . port ;
903- else if ( options . port !== undefined )
904- throw new TypeError ( 'port should be a number or string: ' + options . port ) ;
905-
906- if ( port < 0 || port > 65535 || isNaN ( port ) )
907- throw new RangeError ( 'port should be >= 0 and < 65536: ' +
908- options . port ) ;
908+ port = options . port ;
909+ if ( typeof port !== 'undefined' ) {
910+ if ( typeof port !== 'number' && typeof port !== 'string' )
911+ throw new TypeError ( 'port should be a number or string: ' + port ) ;
912+ if ( ! isLegalPort ( port ) )
913+ throw new RangeError ( 'port should be >= 0 and < 65536: ' + port ) ;
914+ }
915+ port |= 0 ;
909916
910917 if ( dnsopts . family !== 4 && dnsopts . family !== 6 )
911918 dnsopts . hints = dns . ADDRCONFIG | dns . V4MAPPED ;
@@ -1266,11 +1273,16 @@ Server.prototype.listen = function() {
12661273 if ( h . backlog )
12671274 backlog = h . backlog ;
12681275
1269- if ( typeof h . port === 'number' ) {
1276+ if ( typeof h . port === 'number' || typeof h . port === 'string' ||
1277+ ( typeof h . port === 'undefined' && 'port' in h ) ) {
1278+ // Undefined is interpreted as zero (random port) for consistency
1279+ // with net.connect().
1280+ if ( typeof h . port !== 'undefined' && ! isLegalPort ( h . port ) )
1281+ throw new RangeError ( 'port should be >= 0 and < 65536: ' + h . port ) ;
12701282 if ( h . host )
1271- listenAfterLookup ( h . port , h . host , backlog , h . exclusive ) ;
1283+ listenAfterLookup ( h . port | 0 , h . host , backlog , h . exclusive ) ;
12721284 else
1273- listen ( self , null , h . port , 4 , backlog , undefined , h . exclusive ) ;
1285+ listen ( self , null , h . port | 0 , 4 , backlog , undefined , h . exclusive ) ;
12741286 } else if ( h . path && isPipeName ( h . path ) ) {
12751287 var pipeName = self . _pipeName = h . path ;
12761288 listen ( self , pipeName , - 1 , - 1 , backlog , undefined , h . exclusive ) ;
0 commit comments