2

Given an IPv4 or IPv6 address determine if the address is a valid input. This has to be done using Typescript.

I wanted to use an NPM library ip-address as it seemed to meet all of my needs, but i couldnt get it to properly import and use it.

import {ipv4, ipv6} from 'ip-address'

var address = new ipv4(value)
if(address.IsValid){
// do work
}

I expected this to work after importing the npm module, but i get "package not found".

Riley McKenna
  • 31
  • 1
  • 5
  • 4
    Did you install the npm package? –  Jul 03 '19 at 17:55
  • it was installed. i posted the solution. I didnt add it to my @Types – Riley McKenna Jul 03 '19 at 18:01
  • +7.5Mo of NPM packages to validate IPv4 addresses? Mmh... Why not simply use `/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/.match(value)` (or other [more precises regexes](https://www.regular-expressions.info/ip.html))? – Nino Filiu Jul 03 '19 at 18:08
  • I required more than just validating the address using a regex. I needed to know if the address was also in a specific subnet. – Riley McKenna Jul 03 '19 at 18:22

2 Answers2

1

After looking around I found that I was not importing my npm modules correctly.

Using VS19, Open Tools -> VS Command Prompt ->

npm install --save ip-address
npm install --save @types/ip-address

Then in the project file I imported the ip-address following the guidelines.

import * as IpAddress from 'ip-address';
export var ipv4 = IpAddress.Address4;
export var ipv6 = IpAddress.Address6;

then you can just call the var address = new ipv4(value)

Riley McKenna
  • 31
  • 1
  • 5
0

As google ranks this on top for 'typescript type ip address' and the following info also answers the question perfectly (just with another package) I want to note that the package ipaddr.js seems to be smaller and much more common.

Stats according to NPM Trends as of Aug. 2023

package weekly downloads size
ipaddr.js 35.252.234 3.6KB
ip-address 465.104 12.5KB

According to this typescript definitions are included in ipaddr.js since v1.6.0 (2018)

andymel
  • 4,538
  • 2
  • 23
  • 35