Merge pull request #235 from leolin49/master

optimize the impl of ip check and convert
This commit is contained in:
Lion 2022-07-07 09:40:20 +08:00 committed by GitHub
commit 3e35225372
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 10 deletions

View File

@ -5,7 +5,6 @@
package xdb
import (
"encoding/binary"
"fmt"
"strconv"
"strings"
@ -19,7 +18,7 @@ func CheckIP(ip string) (uint32, error) {
return 0, fmt.Errorf("invalid ip address `%s`", ip)
}
var buff = make([]byte, 4)
var val uint32
for i, s := range ps {
d, err := strconv.Atoi(s)
if err != nil {
@ -30,21 +29,16 @@ func CheckIP(ip string) (uint32, error) {
return 0, fmt.Errorf("the %dth part `%s` should be an integer bettween 0 and 255", i, s)
}
buff[i] = byte(d)
val |= uint32(d) << ((3 - i) * 8)
}
// convert the ip to integer
return binary.BigEndian.Uint32(buff), nil
return val, nil
}
func Long2IP(ip uint32) string {
var buff = make([]string, 4)
buff[0] = fmt.Sprintf("%d", (ip>>24)&0xFF)
buff[1] = fmt.Sprintf("%d", (ip>>16)&0xFF)
buff[2] = fmt.Sprintf("%d", (ip>>8)&0xFF)
buff[3] = fmt.Sprintf("%d", (ip>>0)&0xFF)
return strings.Join(buff, ".")
return fmt.Sprintf("%d.%d.%d.%d", (ip>>24)&0xFF, (ip>>16)&0xFF, (ip>>8)&0xFF, (ip>>0)&0xFF)
}
func MidIP(sip uint32, eip uint32) uint32 {

View File

@ -5,10 +5,37 @@
package xdb
import (
"encoding/binary"
"fmt"
"net"
"testing"
)
func TestCheckIP(t *testing.T) {
var str = "29.34.191.255"
ip, err := CheckIP(str)
if err != nil {
t.Errorf("check ip `%s`: %s\n", str, err)
}
netip := net.ParseIP(str).To4()
if netip == nil {
t.Fatalf("parse ip `%s` failed", str)
}
u32 := binary.BigEndian.Uint32(netip)
fmt.Printf("checkip: %d, parseip: %d, isequal: %v", ip, u32, ip == u32)
}
func TestLong2IP(t *testing.T) {
var str = "29.34.191.255"
netip := net.ParseIP(str).To4()
if netip == nil {
t.Fatalf("parse ip `%s` failed", str)
}
u32 := binary.BigEndian.Uint32(netip)
ipstr := Long2IP(u32)
fmt.Printf("originIP: %s, Long2IP: %s, isequal: %v", str, ipstr, ipstr == str)
}
func TestSplitSegment(t *testing.T) {
// var str = "1.1.0.0|1.3.3.24|中国|广东|深圳|电信"
// var str = "0.0.0.0|1.255.225.254|0|0|0|内网IP|内网IP"