ipv6-test-backend/internal/pkg/utils/network.go

88 lines
1.8 KiB
Go
Raw Normal View History

2024-08-18 23:23:18 +08:00
package utils
import (
2024-08-20 13:38:32 +08:00
"encoding/hex"
2024-08-18 23:23:18 +08:00
"errors"
2024-08-20 13:38:32 +08:00
"fmt"
"ipv6-test-node/internal/pkg/protocol"
2024-08-18 23:23:18 +08:00
"net"
2024-08-20 13:38:32 +08:00
"strings"
2024-08-18 23:23:18 +08:00
)
2024-08-20 13:38:32 +08:00
func GetIPVersion(ip net.IP) (protocol.IPVersion, error) {
if ip == nil {
2024-08-18 23:23:18 +08:00
return 0, errors.New("invalid IP address")
}
2024-08-20 13:38:32 +08:00
if ip.To4() != nil {
return protocol.IPv4, nil
} else if ip.To16() != nil {
return protocol.IPv6, nil
2024-08-18 23:23:18 +08:00
} else {
return 0, errors.New("invalid IP address")
}
}
2024-08-20 13:38:32 +08:00
func GetASN(ip protocol.IP) (string, error) {
var query string
if ip.Version == 4 {
query = fmt.Sprintf("%sorigin.asn.cymru.com", reverseIPv4(ip.Address))
} else if ip.Version == 6 {
query = fmt.Sprintf("%sorigin6.asn.cymru.com", reverseIPv6(ip.Address))
}
txtRecords, err := net.LookupTXT(query)
if err != nil {
return "", err
}
if len(txtRecords) > 0 {
parts := strings.Split(txtRecords[0], " | ")
if len(parts) > 0 {
return "AS" + parts[0], nil
}
}
return "", fmt.Errorf("ASN not found")
}
func GetISPName(asn string) (string, error) {
query := fmt.Sprintf("%s.asn.cymru.com", asn)
txtRecords, err := net.LookupTXT(query)
if err != nil {
return "", err
}
if len(txtRecords) > 0 {
parts := strings.Split(txtRecords[0], " | ")
if len(parts) > 0 {
return parts[4], nil
}
}
return "", fmt.Errorf("ISP not found")
}
func ToIP(address net.IP) protocol.IP {
version, err := GetIPVersion(address)
if err != nil {
return protocol.IP{}
}
return protocol.IP{Address: address, Version: version}
}
func reverseIPv4(ip net.IP) string {
return fmt.Sprintf("%d.%d.%d.%d.", ip[3], ip[2], ip[1], ip[0])
}
func reverseIPv6(ip net.IP) string {
var dst []byte
dst = make([]byte, hex.EncodedLen(len(ip)))
hex.Encode(dst, ip)
var reversed string
for i := len(dst) - 1; i >= 0; i-- {
reversed = reversed + string(dst[i]) + "."
}
return reversed
}