重建 common_utils
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
962 B

package common_utils
import (
"fmt"
"net"
"os"
"strings"
)
// ReadIP4 获取ipV4
func ReadIP4() []string {
var ip4 []string
address, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, address := range address {
if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
//log.Println("本机ip:", ipNet.IP.String())
ip4 = append(ip4, ipNet.IP.String())
}
}
}
return ip4
}
// ReadIP4WithPrefix ReadIP4 获取ipV4
// 过滤网段 prefix
func ReadIP4WithPrefix(prefix string) []string {
ip4 := ReadIP4()
var filterIpV4 []string
for _, ip := range ip4 {
if strings.HasPrefix(ip, prefix) {
filterIpV4 = append(filterIpV4, ip)
}
}
return filterIpV4
}
// ReadIP4WithPrefixFirst
// 获取ipV4
// 过滤网段 prefix
func ReadIP4WithPrefixFirst(prefix string) string {
ip4 := ReadIP4WithPrefix(prefix)
if len(ip4) > 0 {
return ip4[0]
}
return ""
}