Created
December 22, 2014 12:00
-
-
Save nathan-muir/13195bc5b7ae07a48885 to your computer and use it in GitHub Desktop.
Inet.coffee
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
IP_ADDRESS_REGEX = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/ | |
CIDR_ADDRESS_REGEX = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/ | |
class @Inet | |
constructor: (ipAddress)-> | |
if typeof ipAddress == 'number' | |
@ipAddressNumber = ipAddress | |
@ipAddress = Inet.numberToAddress(ipAddress) | |
else | |
@ipAddress = ipAddress | |
@ipAddressNumber = Inet.addressToNumber(ipAddress) | |
isInSubNet: (subnetCidr) -> | |
{ipAddressNumber: subNetAddress, mask: mask} = Inet.subNetToNumberAndMask(subnetCidr) | |
return (@ipAddressNumber & mask) == (subNetAddress & mask) | |
isPrivateAddress: ()-> | |
@isInSubNet('127.0.0.1/0') or @isInSubNet('10.0.0.0/24') or @isInSubNet('172.16.0.0/20') or @isInSubNet('192.168.0.0/16') | |
@addressToNumber: (ipAddress)-> | |
components = ipAddress.match(IP_ADDRESS_REGEX) | |
unless components? | |
throw new Error("Not a valid IPv4 Address '#{ipAddress}'") | |
components.shift() #destroy first entry | |
ipAddressNumber = 0 | |
multiplicand = 1 | |
for component in components | |
ipAddressNumber += parseInt(component) * multiplicand | |
multiplicand *= 256 | |
return ipAddressNumber | |
@numberToAddress: (ipAddressNumber)-> | |
components = [] | |
for i in [3...0] | |
components[i] = (ipAddressNumber % 256).toFixed(0) | |
ipAddressNumber = Math.floor(ipAddressNumber / 256) | |
return components.join('.') | |
@subNetToNumberAndMask: (subnetCidr)-> | |
matches = subnetCidr.match(CIDR_ADDRESS_REGEX) | |
unless matches? | |
throw new Error("Not a valid IPv4 CIDR Notation '#{subnetCidr}'") | |
[tmp, ipAddress, prefixSize] = matches | |
return { | |
ipAddressNumber: Inet.addressToNumber(ipAddress), | |
mask: Inet.prefixSizeToMask(prefixSize) | |
} | |
@prefixSizeToMask: (prefixSize)-> | |
return ((1 << (32 - prefixSize)) - 1) ^ 0xFFFFFFFF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment