golang 判断ip、内网ip

浪尽此生 提交于 2020-03-01 11:07:37

实现如下

package main

import (
   "fmt"
   "net"
   "strconv"
   "strings"
)

func checkIp(ipStr string) bool {
   address := net.ParseIP(ipStr)
   if address == nil {
      fmt.Println("ip地址格式不正确")
      return false
   } else {
      fmt.Println("正确的ip地址", address.String())
      return true
   }
}

// ip to int64
func inetAton(ipStr string) int64 {
   bits := strings.Split(ipStr, ".")

   b0, _ := strconv.Atoi(bits[0])
   b1, _ := strconv.Atoi(bits[1])
   b2, _ := strconv.Atoi(bits[2])
   b3, _ := strconv.Atoi(bits[3])

   var sum int64

   sum += int64(b0) << 24
   sum += int64(b1) << 16
   sum += int64(b2) << 8
   sum += int64(b3)

   return sum
}

//int64 to IP
func inetNtoa(ipnr int64) net.IP {
   var bytes [4]byte
   bytes[0] = byte(ipnr & 0xFF)
   bytes[1] = byte((ipnr >> 8) & 0xFF)
   bytes[2] = byte((ipnr >> 16) & 0xFF)
   bytes[3] = byte((ipnr >> 24) & 0xFF)

   return net.IPv4(bytes[3], bytes[2], bytes[1], bytes[0])
}

func isInnerIp(ipStr string) bool {
   if !checkIp(ipStr) {
      return false
   }
   inputIpNum := inetAton(ipStr)
   innerIpA := inetAton("10.255.255.255")
   innerIpB := inetAton("172.16.255.255")
   innerIpC := inetAton("192.168.255.255")
   innerIpD := inetAton("100.64.255.255")
   innerIpF := inetAton("127.255.255.255")
  
   return inputIpNum>>24 == innerIpA>>24 || inputIpNum>>20 == innerIpB>>20 ||
      inputIpNum>>16 == innerIpC>>16 || inputIpNum>>22 == innerIpD>>22 ||
      inputIpNum>>24 == innerIpF>>24 
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!