-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
275 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
'use strict'; | ||
|
||
|
||
/** | ||
* @param {string} hostname | ||
* @return {boolean} | ||
*/ | ||
function isProbablyIpv4(hostname) { | ||
var numberOfDots = 0; | ||
|
||
for (var i = 0; i < hostname.length; i += 1) { | ||
var code = hostname.charCodeAt(i); | ||
|
||
if (code === 46) { // '.' | ||
numberOfDots += 1; | ||
} else if (code < 48 || code > 57) { | ||
// 48 => '0' | ||
// 57 => '9' | ||
return false; | ||
} | ||
} | ||
|
||
return ( | ||
numberOfDots === 3 && | ||
hostname[0] !== '.' && | ||
hostname[hostname.length - 1] !== '.' | ||
); | ||
} | ||
|
||
|
||
/** | ||
* @param {string} hostname | ||
* @return {boolean} | ||
*/ | ||
function isProbablyIpv6(hostname) { | ||
var hasColon = false; | ||
|
||
for (var i = 0; i < hostname.length; i += 1) { | ||
var code = hostname.charCodeAt(i); | ||
|
||
if (code === 58) { // ':' | ||
hasColon = true; | ||
} else if (!( | ||
(code >= 48 && code <= 57) || // 0-9 | ||
(code >= 97 && code <= 102) // a-f | ||
)) { | ||
return false; | ||
} | ||
} | ||
|
||
return hasColon; | ||
} | ||
|
||
|
||
/** | ||
* Check if `hostname` is a valid ip addr (either ipv6 or ipv4). | ||
* | ||
* @param {string} hostname | ||
* @return {boolean} | ||
*/ | ||
module.exports = function isIp(hostname) { | ||
if (typeof hostname !== 'string') { | ||
return false; | ||
} | ||
|
||
if (hostname.length === 0) { | ||
return false; | ||
} | ||
|
||
return (isProbablyIpv6(hostname) || isProbablyIpv4(hostname)); | ||
}; |
Oops, something went wrong.