Go – check if IP address is in a network

Issue

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:

UPDATE March 2022
👉 for Go 1.18, check the answer below by blackgreen

Solution

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.

Answered By – Zoyd

Answer Checked By – Gilberto Lyons (GoLangFix Admin)

Leave a Reply

Your email address will not be published.