2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2017-12-29 16:03:30 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2017-12-29 16:03:30 +08:00
|
|
|
//
|
2017-12-31 18:19:58 +08:00
|
|
|
|
2019-01-15 23:27:47 +08:00
|
|
|
// Package gipv4 provides useful API for IPv4 address handling.
|
2017-12-14 17:32:51 +08:00
|
|
|
package gipv4
|
2017-11-23 10:21:28 +08:00
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"encoding/binary"
|
|
|
|
"fmt"
|
2020-05-16 15:35:21 +08:00
|
|
|
"github.com/gogf/gf/text/gregex"
|
2019-06-19 09:06:52 +08:00
|
|
|
"net"
|
|
|
|
"strconv"
|
2017-11-23 10:21:28 +08:00
|
|
|
)
|
|
|
|
|
2019-10-30 19:55:50 +08:00
|
|
|
// Ip2long converts ip address to an uint32 integer.
|
2020-01-13 14:50:06 +08:00
|
|
|
func Ip2long(ip string) uint32 {
|
|
|
|
netIp := net.ParseIP(ip)
|
|
|
|
if netIp == nil {
|
2019-06-19 09:06:52 +08:00
|
|
|
return 0
|
|
|
|
}
|
2020-01-13 14:50:06 +08:00
|
|
|
return binary.BigEndian.Uint32(netIp.To4())
|
2017-11-23 10:21:28 +08:00
|
|
|
}
|
|
|
|
|
2019-10-30 19:55:50 +08:00
|
|
|
// Long2ip converts an uint32 integer ip address to its string type address.
|
2020-01-13 14:50:06 +08:00
|
|
|
func Long2ip(long uint32) string {
|
2019-06-19 09:06:52 +08:00
|
|
|
ipByte := make([]byte, 4)
|
2020-01-13 14:50:06 +08:00
|
|
|
binary.BigEndian.PutUint32(ipByte, long)
|
2019-06-19 09:06:52 +08:00
|
|
|
return net.IP(ipByte).String()
|
2017-11-23 10:21:28 +08:00
|
|
|
}
|
|
|
|
|
2020-05-16 15:35:21 +08:00
|
|
|
// Validate checks whether given <ip> a valid IPv4 address.
|
|
|
|
func Validate(ip string) bool {
|
|
|
|
return gregex.IsMatchString(`^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$`, ip)
|
2017-11-23 10:21:28 +08:00
|
|
|
}
|
|
|
|
|
2019-10-30 19:55:50 +08:00
|
|
|
// ParseAddress parses <address> to its ip and port.
|
|
|
|
// Eg: 192.168.1.1:80 -> 192.168.1.1, 80
|
|
|
|
func ParseAddress(address string) (string, int) {
|
|
|
|
match, err := gregex.MatchString(`^(.+):(\d+)$`, address)
|
|
|
|
if err == nil {
|
|
|
|
i, _ := strconv.Atoi(match[2])
|
|
|
|
return match[1], i
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
return "", 0
|
2017-11-23 10:21:28 +08:00
|
|
|
}
|
|
|
|
|
2020-05-16 15:35:21 +08:00
|
|
|
// GetSegment returns the segment of given ip address.
|
|
|
|
// Eg: 192.168.2.102 -> 192.168.2
|
|
|
|
func GetSegment(ip string) string {
|
|
|
|
match, err := gregex.MatchString(`^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$`, ip)
|
|
|
|
if err != nil || len(match) < 4 {
|
|
|
|
return ""
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2020-05-16 15:35:21 +08:00
|
|
|
return fmt.Sprintf("%s.%s.%s", match[1], match[2], match[3])
|
2017-11-23 10:21:28 +08:00
|
|
|
}
|