github.com/wangyougui/gf/v2@v2.6.5/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/wangyougui/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 "net" 15 "strconv" 16 17 "github.com/wangyougui/gf/v2/text/gregex" 18 ) 19 20 // Ip2long converts ip address to an uint32 integer. 21 func Ip2long(ip string) uint32 { 22 netIp := net.ParseIP(ip) 23 if netIp == nil { 24 return 0 25 } 26 return binary.BigEndian.Uint32(netIp.To4()) 27 } 28 29 // Long2ip converts an uint32 integer ip address to its string type address. 30 func Long2ip(long uint32) string { 31 ipByte := make([]byte, 4) 32 binary.BigEndian.PutUint32(ipByte, long) 33 return net.IP(ipByte).String() 34 } 35 36 // Validate checks whether given `ip` a valid IPv4 address. 37 func Validate(ip string) bool { 38 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) 39 } 40 41 // ParseAddress parses `address` to its ip and port. 42 // Eg: 192.168.1.1:80 -> 192.168.1.1, 80 43 func ParseAddress(address string) (string, int) { 44 match, err := gregex.MatchString(`^(.+):(\d+)$`, address) 45 if err == nil { 46 i, _ := strconv.Atoi(match[2]) 47 return match[1], i 48 } 49 return "", 0 50 } 51 52 // GetSegment returns the segment of given ip address. 53 // Eg: 192.168.2.102 -> 192.168.2 54 func GetSegment(ip string) string { 55 match, err := gregex.MatchString(`^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$`, ip) 56 if err != nil || len(match) < 4 { 57 return "" 58 } 59 return fmt.Sprintf("%s.%s.%s", match[1], match[2], match[3]) 60 }