gipv4.go 1.6 KB

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