-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipv4.go
53 lines (46 loc) · 1.39 KB
/
ipv4.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Package ipv4 provides useful API for IPv4 address handling.
package ipv4
import (
"encoding/binary"
"fmt"
"net"
"strconv"
"github.com/xwc1125/xwc1125-pkg/utils/regexutil"
)
// Ip2long converts ip address to an uint32 integer.
func Ip2long(ip string) uint32 {
netIp := net.ParseIP(ip)
if netIp == nil {
return 0
}
return binary.BigEndian.Uint32(netIp.To4())
}
// Long2ip converts an uint32 integer ip address to its string type address.
func Long2ip(long uint32) string {
ipByte := make([]byte, 4)
binary.BigEndian.PutUint32(ipByte, long)
return net.IP(ipByte).String()
}
// Validate checks whether given `ip` a valid IPv4 address.
func Validate(ip string) bool {
return regexutil.IsMatchString(`^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$`, ip)
}
// 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 := regexutil.MatchString(`^(.+):(\d+)$`, address)
if err == nil {
i, _ := strconv.Atoi(match[2])
return match[1], i
}
return "", 0
}
// GetSegment returns the segment of given ip address.
// Eg: 192.168.2.102 -> 192.168.2
func GetSegment(ip string) string {
match, err := regexutil.MatchString(`^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$`, ip)
if err != nil || len(match) < 4 {
return ""
}
return fmt.Sprintf("%s.%s.%s", match[1], match[2], match[3])
}