• Stars
    star
    528
  • Rank 81,960 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 13 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

IP address manipulation library in JavaScript

ipaddr.js — an IPv6 and IPv4 address manipulation library

Build Status

ipaddr.js is a small (1.9K minified and gzipped) library for manipulating IP addresses in JavaScript environments. It runs on both CommonJS runtimes (e.g. nodejs) and in a web browser.

ipaddr.js allows you to verify and parse string representation of an IP address, match it against a CIDR range or range list, determine if it falls into some reserved ranges (examples include loopback and private ranges), and convert between IPv4 and IPv4-mapped IPv6 addresses.

Installation

npm install ipaddr.js

or

bower install ipaddr.js

Older Node support

Use 2.x release for nodejs versions 10+. Use the 1.x release for versions of nodejs older than 10.

API

ipaddr.js defines one object in the global scope: ipaddr. In CommonJS, it is exported from the module:

const ipaddr = require('ipaddr.js');

The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4.

Global methods

There are three global methods defined: ipaddr.isValid, ipaddr.parse and ipaddr.process. All of them receive a string as a single parameter.

The ipaddr.isValid method returns true if the address is a valid IPv4 or IPv6 address, and false otherwise. It does not throw any exceptions.

The ipaddr.parse method returns an object representing the IP address, or throws an Error if the passed string is not a valid representation of an IP address.

The ipaddr.process method works just like the ipaddr.parse one, but it automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts before returning. It is useful when you have a Node.js instance listening on an IPv6 socket, and the net.ivp6.bindv6only sysctl parameter (or its equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 connections on your IPv6-only socket, but the remote address will be mangled. Use ipaddr.process method to automatically demangle it.

Object representation

Parsing methods return an object which descends from ipaddr.IPv6 or ipaddr.IPv4. These objects share some properties, but most of them differ.

Shared properties

One can determine the type of address by calling addr.kind(). It will return either "ipv6" or "ipv4".

An address can be converted back to its string representation with addr.toString(). Note that this method:

  • does not return the original string used to create the object (in fact, there is no way of getting that string)
  • returns a compact representation (when it is applicable)

A match(range, bits) method can be used to check if the address falls into a certain CIDR range. Note that an address can be (obviously) matched only against an address of the same type.

For example:

const addr  = ipaddr.parse('2001:db8:1234::1');
const range = ipaddr.parse('2001:db8::');

addr.match(range, 32); // => true

Alternatively, match can also be called as match([range, bits]). In this way, it can be used together with the parseCIDR(string) method, which parses an IP address together with a CIDR range.

For example:

const addr = ipaddr.parse('2001:db8:1234::1');

addr.match(ipaddr.parseCIDR('2001:db8::/32')); // => true

A range() method returns one of predefined names for several special ranges defined by IP protocols. The exact names (and their respective CIDR ranges) can be looked up in the source: IPv6 ranges and IPv4 ranges. Some common ones include "unicast" (the default one) and "reserved".

You can match against your own range list by using ipaddr.subnetMatch(address, rangeList, defaultName) method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example:

const rangeList = {
  documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ],
  tunnelProviders: [
    [ ipaddr.parse('2001:470::'), 32 ], // he.net
    [ ipaddr.parse('2001:5c0::'), 32 ]  // freenet6
  ]
};
ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders"

The addresses can be converted to their byte representation with toByteArray(). (Actually, JavaScript mostly does not know about byte buffers. They are emulated with arrays of numbers, each in range of 0..255.)

const bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com
bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, <zeroes...>, 0x00, 0x68 ]

The ipaddr.IPv4 and ipaddr.IPv6 objects have some methods defined, too. All of them have the same interface for both protocols, and are similar to global methods.

ipaddr.IPvX.isValid(string) can be used to check if the string is a valid address for particular protocol, and ipaddr.IPvX.parse(string) is the error-throwing parser.

ipaddr.IPvX.isValid(string) uses the same format for parsing as the POSIX inet_ntoa function, which accepts unusual formats like 0xc0.168.1.1 or 0x10000000. The function ipaddr.IPv4.isValidFourPartDecimal(string) validates the IPv4 address and also ensures that it is written in four-part decimal format.

IPv6 properties

Sometimes you will want to convert IPv6 not to a compact string representation (with the :: substitution); the toNormalizedString() method will return an address where all zeroes are explicit.

For example:

const addr = ipaddr.parse('2001:0db8::0001');
addr.toString(); // => '2001:db8::1'
addr.toNormalizedString(); // => '2001:db8:0:0:0:0:0:1'

The isIPv4MappedAddress() method will return true if this address is an IPv4-mapped one, and toIPv4Address() will return an IPv4 object address.

To access the underlying binary representation of the address, use addr.parts.

const addr = ipaddr.parse('2001:db8:10::1234:DEAD');
addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead]

A IPv6 zone index can be accessed via addr.zoneId:

const addr = ipaddr.parse('2001:db8::%eth0');
addr.zoneId // => 'eth0'

IPv4 properties

toIPv4MappedAddress() will return a corresponding IPv4-mapped IPv6 address.

To access the underlying representation of the address, use addr.octets.

const addr = ipaddr.parse('192.168.1.1');
addr.octets // => [192, 168, 1, 1]

prefixLengthFromSubnetMask() will return a CIDR prefix length for a valid IPv4 netmask or null if the netmask is not valid.

ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28
ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask()  == null

subnetMaskFromPrefixLength() will return an IPv4 netmask for a valid CIDR prefix length.

ipaddr.IPv4.subnetMaskFromPrefixLength(24) == '255.255.255.0'
ipaddr.IPv4.subnetMaskFromPrefixLength(29) == '255.255.255.248'

broadcastAddressFromCIDR() will return the broadcast address for a given IPv4 interface and netmask in CIDR notation.

ipaddr.IPv4.broadcastAddressFromCIDR('172.0.0.1/24') == '172.0.0.255'

networkAddressFromCIDR() will return the network address for a given IPv4 interface and netmask in CIDR notation.

ipaddr.IPv4.networkAddressFromCIDR('172.0.0.1/24') == '172.0.0.0'

Conversion

IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays.

The fromByteArray() method will take an array and create an appropriate IPv4 or IPv6 object if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, while for IPv6 it has to be an array of sixteen 8-bit values.

For example:

const addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]);
addr.toString(); // => '127.0.0.1'

or

const addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
addr.toString(); // => '2001:db8::1'

Both objects also offer a toByteArray() method, which returns an array in network byte order (MSB).

For example:

const addr = ipaddr.parse('127.0.0.1');
addr.toByteArray(); // => [0x7f, 0, 0, 1]

or

const addr = ipaddr.parse('2001:db8::1');
addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]

More Repositories

1

parser

A Ruby parser.
Yacc
1,565
star
2

unfork

unfork(2) is the inverse of fork(2). sort of.
C++
1,435
star
3

rack-utf8_sanitizer

Rack::UTF8Sanitizer is a Rack middleware which cleans up invalid UTF8 characters in request URI and headers.
Ruby
298
star
4

irclogger

Simple and good-looking IRC log viewer. Logger is included. No strings are attached.
Ruby
252
star
5

ast

A library for working with Abstract Syntax Trees.
Ruby
193
star
6

kicad-boardview

KiCAD to Boardview exporter reads KiCAD PCB layout files and writes ASCII Boardview files
Python
150
star
7

rust-xdg

A library that makes it easy to follow the X Desktop Group specifications
Rust
145
star
8

rust-vnc

An implementation of VNC protocol, client state machine, a client and a proxy
Rust
127
star
9

Boneless-CPU

Resource-efficient 16-bit CPU architecture for FPGA control plane
Python
92
star
10

zmtp-wireshark

A Wireshark dissector for ZMTP version 3.0 and later (ZeroMQ 4 and later)
Lua
82
star
11

furnace-avm2

Flash ActionScript3 VM static analysis library based on Furnace framework.
Ruby
76
star
12

libfx2

Chip support package for Cypress EZ-USB FX2 series microcontrollers
C
69
star
13

binja_itanium_cxx_abi

Binary Ninja Itanium C++ ABI Plugin
Python
62
star
14

coldruby

ColdRuby is a compiler of Ruby 1.9 MRI bytecode, and a runtime written in JavaScript to aid in execution of Ruby code. It also includes a C++ executable using very fast V8 scripting engine and native extensions for regular expressions, fibers and more.
JavaScript
62
star
15

Yumewatari

妖刀夢渡
Python
54
star
16

ocaml-m17n

Multilingualization for the OCaml source code
OCaml
52
star
17

rust-log_buffer

A zero-allocation ring buffer for storing text logs, implemented in Rust
Rust
51
star
18

prjbureau

Documenting the Microchip (Atmel) ATF15xx CPLD fuse maps and programming algorithms
Python
47
star
19

rust-facedetect

A primer on using OpenCV with Rust
Rust
43
star
20

groupXIV

Microphotography viewer based on Leaflet.js
JavaScript
41
star
21

ocaml-inotify

OCaml bindings for inotify.
OCaml
36
star
22

python-itanium_demangler

Pure Python Itanium C++ ABI demangler
Python
33
star
23

ocaml-llvm-ng

A practical LLVM backend for OCaml (will never be finished)
OCaml
33
star
24

SIPCaller

A simple Android app to call SIP numbers directly
Java
31
star
25

infra-vpn

Automation for WireGuard VPN tunnels
30
star
26

rlua

Ruby to Lua bindings library.
C
27
star
27

js_of_ocaml-example

A tiny sample js_of_ocaml project
OCaml
26
star
28

ocaml-lz4

OCaml bindings for LZ4, a very fast lossless compression algorithm
OCaml
26
star
29

binja-avnera

Binary Ninja plugin for the Avnera AV6xxx/AV7xxx architecture
Python
25
star
30

icefloorplan

iCE40 floorplan viewer
C++
24
star
31

sublime-better-ocaml

Default Sublime Text highlighting for OCaml sucks. I've fixed it.
23
star
32

tf2_healslut

C++
22
star
33

gameboy-grabber

Rust
20
star
34

furnace

A static analysis framework.
Ruby
18
star
35

sublime-ocp-index

Sublime Text plugin which provides OCaml autocompletion with ocp-index
Python
17
star
36

ATF15xx-EVB

Cheap & simple evaluation boards for Microchip ATF15xx CPLDs
16
star
37

zs

ZYTOKINE STORM is a user-mode Linux binary translation layer targeting Darwin
C++
16
star
38

binja-m16c

Binary Ninja plugin for the Renesas M16C architecture
Python
15
star
39

opam-query

A tool to query opam files from shell scripts
OCaml
15
star
40

bfcpu2

A pipelined brainfuck softcore in Verilog
Verilog
14
star
41

binja-i8086

16-bit x86 architecture for Binary Ninja
Python
13
star
42

cylinder

OCaml
13
star
43

sublime-imethod-fix

→ Makes XCompose work in Sublime Text! ←
C
13
star
44

ocaml-protobuf

Google Protocol Buffers runtime implemented in OCaml
OCaml
12
star
45

lab-notebook

Source for my lab notebook
JavaScript
12
star
46

story-os

A microkernel OS for x86 I wrote in C++ back in 2007. Features VMM, TSS multitasking, and oddly shaped C++. Updated in 2023 to fix some memory management bugs and now it works.
C
11
star
47

binja_extended_api

Extended Python API for Binary Ninja
Python
10
star
48

sparkle

Sparkle is a zero-configuration decentralized VPN which can tunnel IP packets, simultaneously handle multiple payload types like VoIP or IM (together with tunneling) and be embedded anywhere as a small library.
C
10
star
49

ocaml-expat

The official repository of the ocaml-expat library
OCaml
9
star
50

unrandom

Make srand() always use the seed 0 using LD_PRELOAD
C
9
star
51

murmurhash3-js

JavaScript implementation of MurmurHash3
JavaScript
9
star
52

lend

Allocator
C
9
star
53

libstm32

A reimplementation of standard library for STM32 family Cortex-M3 processors.
C
9
star
54

catircservices.org

Nix configuration for a Matrix<>IRC and Matrix<>Discord bridge
Nix
7
star
55

libnrf24l

Chip support package for Nordic nRF24L series microcontrollers
C++
7
star
56

Sublime-Yesterday-Theme

whitequark's fork of Tomorrow color scheme
7
star
57

eliom-example

Eliom example application
OCaml
7
star
58

infra-server

Ansible configuration for https://whitequark.org
Shell
7
star
59

pry.ml

OCaml
7
star
60

usbasp

Thomas Fischl's USBasp (orig. http://www.fischl.de/usbasp/) with my patches.
C
6
star
61

binja_function_abi

Binary Ninja plugin for viewing and changing function ABIs in a fine-grained way via the GUI
Python
6
star
62

LineageOS_vendor_whitequark

My LineageOS overlay
Shell
6
star
63

furnace-swf

A rudimentary SWF reader for furnace-avm2.
Ruby
6
star
64

rust-touptek

Rust bindings for Touptek ToupLite image acquisition library
Rust
6
star
65

LLVM-TableGen.tmBundle

LLVM TableGen syntax definition
5
star
66

sdcc

Git mirror of http://svn.code.sf.net/p/sdcc/code/trunk
C
5
star
67

usbasploader

Objective Development's USBaspLoader (orig. http://www.obdev.at/products/vusb/usbasploader.html) with my patches.
C
5
star
68

track-pypi-dependency-version

A script for use with GitHub Actions that updates the upper bound in requirements.txt when a package is released on PyPI
Python
5
star
69

ruby-cross-reference

Sources for the Ruby Cross Reference LXR setup
Perl
5
star
70

ocaml-cavalry

Marshaling experiment
OCaml
5
star
71

vuxboot

VuXboot is a small but powerful AVR UART bootloader.
C++
4
star
72

Sublime-JESD3

JEDEC JESD3 syntax highlighter for Sublime Text 3
4
star
73

sphinxcontrib-platformpicker

Platform picker extension for Sphinx
Python
4
star
74

samplerate-rs

Rust bindings for libsamplerate
Rust
4
star
75

i3gamma

i3gamma integrates with the i3 window manager and changes the gamma correction value depending on the focused window
Rust
4
star
76

disable_eval

The only safe eval is no eval.
Ruby
3
star
77

cyberplat_pki

CyberplatPKI is a library for signing Cyberplat requests.
Ruby
3
star
78

suwabara

Ruby
3
star
79

unbot

Ruby
3
star
80

binja_xapi_bookmarks

Binary Ninja bookmarks plugin that integrates into the GUI
Python
3
star
81

Leaflet.Nanoscale

Sub-millimeter scale indicator for Leaflet.js
JavaScript
2
star
82

blog

http://whitequark.org
Ruby
2
star
83

Sublime-S-Expressions

Sublime Text 3 syntax definition for S-Expressions
2
star
84

bacon-colored_output

Colored output for Bacon testing framework!
Ruby
2
star
85

whimper

OCaml
2
star
86

linux5be

Remains of a failed attempt to port Linux to BE-300. WARNING: Doing so may result in severe frustration
2
star
87

catirclogs.org

(WIP) Nix configuration for IRC logging infrastructure
Nix
1
star
88

pcbhdl

Python toolbox for designing printed circuit boards
Python
1
star
89

50w-modular-psu

A modular high-voltage PSU, rated at 50W continuous power
Processing
1
star
90

ocaml-eval_in

An http://eval.in/ bot in OCaml.
OCaml
1
star
91

vacuum-induction-furnace

CAD files for a vacuum induction furnace with capacity of 50mL
HTML
1
star
92

Shinobu

1
star
93

n250-dsdt

Samsung N250 ACPI DSDT
1
star
94

cmake-ocaml-simple

Simple, inflexible and non-expressive OCaml rules for CMake. Originally developed for LLVM CMake builds.
CMake
1
star