Golang - check if IP address is in a network

tgogos picture tgogos · Apr 7, 2017 · Viewed 14.4k times · Source

Given:

  • a network address A: (172.17.0.0/16)
  • and an IP address from a host B: (172.17.0.2/16)

how can we say if B is in A?

All addresses are string variables in the following form: [IP address in dot-decimal notation]/[subnet mask]. Should I try to do it by manipulating strings (initial thoughts). Is there a different path?

Here is the same question for Python:

and another approach with Go:

Answer

Zoyd picture Zoyd · Apr 7, 2017

The Go net package includes the following functions:

  • ParseCIDR: takes a string representing an IP/mask and returns an IP and an IPNet
  • IPNet.Contains: checks whether an IP is in a network

This should cover your needs.