Go quickly judges whether an IP is in a given network segment

You can Gouse netthe package in the language to determine IPwhether is within a given network segment. Specific steps are as follows:

  • Use net.ParseCIDR()the method to parse the given network segment and return IPthe address and subnet mask of the network segment.
  • Use net.ParseIP()the method to parse IPthe address to be judged.
  • Use net.IPNet.Contains()the method to judge IPwhether the address to be judged is in the network segment.

Here is a sample code:

package main

import (
	"fmt"
	"net"
)

func main() {
    
    
	ip := net.ParseIP("192.168.0.1")
	_, ipNet, _ := net.ParseCIDR("192.168.0.0/24")

	if ipNet.Contains(ip) {
    
    
		fmt.Println("IP is in subnet")
	} else {
    
    
		fmt.Println("IP is not in subnet")
	}
}

In this example, IPthe address 192.168.0.1, and the network segment to be judged is parsed 192.168.0.0/24, and then net.IPNet.Contains()the method to judge IPwhether the address is in the network segment. If it is in the network segment, output IP is in subnet, otherwise output IP is not in subnet.

Tips: I have to say that Golangthe code looks really concise. Although there are a lot of actual business codes when writing return, hahaha, it is very comfortable to write.

Personal blog: Roc's Blog

Guess you like

Origin blog.csdn.net/peng2hui1314/article/details/129085957