github.com/gogf/gf@v1.16.9/net/gipv4/gipv4.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 // 7 8 // Package gipv4 provides useful API for IPv4 address handling. 9 package gipv4 10 11 import ( 12 "encoding/binary" 13 "fmt" 14 "github.com/gogf/gf/text/gregex" 15 "net" 16 "strconv" 17 ) 18 19 // Ip2long converts ip address to an uint32 integer. 20 func Ip2long(ip string) uint32 { 21 netIp := net.ParseIP(ip) 22 if netIp == nil { 23 return 0 24 } 25 return binary.BigEndian.Uint32(netIp.To4()) 26 } 27 28 // Long2ip converts an uint32 integer ip address to its string type address. 29 func Long2ip(long uint32) string { 30 ipByte := make([]byte, 4) 31 binary.BigEndian.PutUint32(ipByte, long) 32 return net.IP(ipByte).String() 33 } 34 35 // Validate checks whether given <ip> a valid IPv4 address. 36 func Validate(ip string) bool { 37 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) 38 } 39 40 // ParseAddress parses <address> to its ip and port. 41 // Eg: 192.168.1.1:80 -> 192.168.1.1, 80 42 func ParseAddress(address string) (string, int) { 43 match, err := gregex.MatchString(`^(.+):(\d+)$`, address) 44 if err == nil { 45 i, _ := strconv.Atoi(match[2]) 46 return match[1], i 47 } 48 return "", 0 49 } 50 51 // GetSegment returns the segment of given ip address. 52 // Eg: 192.168.2.102 -> 192.168.2 53 func GetSegment(ip string) string { 54 match, err := gregex.MatchString(`^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$`, ip) 55 if err != nil || len(match) < 4 { 56 return "" 57 } 58 return fmt.Sprintf("%s.%s.%s", match[1], match[2], match[3]) 59 }