增强IP相关函数

This commit is contained in:
刘祥超
2024-04-06 14:57:18 +08:00
parent cc0b2fd74f
commit a600fc9cd3
2 changed files with 61 additions and 0 deletions

View File

@@ -3,6 +3,7 @@
package iputils
import (
"bytes"
"encoding/binary"
"encoding/hex"
"math"
@@ -53,6 +54,10 @@ func IsIPv6(ipString string) bool {
return rawIP != nil && rawIP.To4() == nil && rawIP.To16() != nil
}
func IsValid(ipString string) bool {
return net.ParseIP(ipString) != nil
}
func CompareLong(i1 string, i2 string) int {
if i1 == "" {
i1 = "0"
@@ -105,6 +110,9 @@ func ToLong(ip string) string {
}
func ToHex(ip string) string {
if len(ip) == 0 {
return ""
}
var rawIP = net.ParseIP(ip)
if rawIP == nil {
return ""
@@ -117,6 +125,38 @@ func ToHex(ip string) string {
return hex.EncodeToString(rawIP.To16())
}
func ToBytes(ip string) []byte {
if len(ip) == 0 {
return nil
}
var rawIP = net.ParseIP(ip)
if rawIP == nil {
return nil
}
if rawIP.To4() != nil {
return rawIP.To4()
}
return rawIP.To16()
}
func CompareBytes(b1 []byte, b2 []byte) int {
var l1 = len(b1)
var l2 = len(b2)
if l1 < l2 {
return -1
}
if l1 > l2 {
return 1
}
return bytes.Compare(b1, b2)
}
func CompareIP(ip1 string, ip2 string) int {
return CompareBytes(ToBytes(ip1), ToBytes(ip2))
}
func ToLittleLong(ip string) string {
var rawIP = net.ParseIP(ip)
if rawIP == nil {

View File

@@ -21,6 +21,7 @@ func TestIP_ParseIP(t *testing.T) {
a.IsFalse(iputils.IsIPv6("127.0.0.1"))
t.Log(i.String(), i.ToLong())
t.Log("raw:", i.Raw())
a.IsTrue(iputils.IsValid("127.0.0.1"))
}
{
@@ -63,6 +64,7 @@ func TestIP_ParseIP(t *testing.T) {
a.IsFalse(i.IsIPv4())
a.IsTrue(i.IsIPv6())
a.IsTrue(i.IsValid())
a.IsTrue(iputils.IsValid("2001:db8:0:1::2:101"))
}
}
@@ -72,6 +74,7 @@ func TestIP_ParseIP(t *testing.T) {
a.IsFalse(i.IsIPv4())
a.IsFalse(i.IsIPv6())
a.IsFalse(i.IsValid())
a.IsFalse(iputils.IsValid("WRONG IP"))
a.IsFalse(iputils.IsIPv4("WRONG IP"))
a.IsFalse(iputils.IsIPv6("WRONG IP"))
}
@@ -208,6 +211,24 @@ func TestIP_Memory(t *testing.T) {
}
}
func TestToBytes(t *testing.T) {
var a = assert.NewAssertion(t)
a.IsTrue(len(iputils.ToBytes("a")) == 0)
a.IsTrue(len(iputils.ToBytes("192.168.1.100")) == 4)
a.IsTrue(len(iputils.ToBytes("::1")) == 16)
}
func TestCompareIP(t *testing.T) {
var a = assert.NewAssertion(t)
a.IsTrue(iputils.CompareIP("a", "b") == 0)
a.IsTrue(iputils.CompareIP("192.168.1.100", "192.168.1.1") > 0)
a.IsTrue(iputils.CompareIP("192.168.1.100", "10.168.1.1") > 0)
a.IsTrue(iputils.CompareIP("192.168.1.100", "192.168.2.1") < 0)
a.IsTrue(iputils.CompareIP("192.168.1.100", "::1") < 0)
a.IsTrue(iputils.CompareIP("::1", "192.168.1.100") > 0)
a.IsTrue(iputils.CompareIP("192.168.1.100", "192.168.1.100") == 0)
}
func BenchmarkParse(b *testing.B) {
for i := 0; i < b.N; i++ {
iputils.ParseIP("fd00:6868:6868:0:10ac:d056:3bf6:7452")