better infinity mode implementation

This commit is contained in:
juzeon
2024-02-12 10:13:18 -05:00
committed by yuhan6665
parent 8e0e975703
commit 1b3f818b21
3 changed files with 82 additions and 14 deletions
+78
View File
@@ -3,8 +3,11 @@ package main
import (
"bufio"
"errors"
"fmt"
"io"
"log/slog"
"math"
"math/big"
"net"
"net/netip"
"regexp"
@@ -108,6 +111,67 @@ func ExistOnlyOne(arr []string) bool {
}
return exist
}
func IterateAddr(addr string) <-chan Host {
hostChan := make(chan Host)
_, _, err := net.ParseCIDR(addr)
if err == nil {
// is CIDR
return Iterate(strings.NewReader(addr))
}
ip := net.ParseIP(addr)
if ip == nil {
ip, err = LookupIP(addr)
if err != nil {
close(hostChan)
slog.Error("Not a valid IP, IP CIDR or domain", "addr", addr)
return hostChan
}
}
go func() {
slog.Info("Enable infinite mode", "init", ip.String())
lowIP := ip
highIP := ip
hostChan <- Host{
IP: ip,
Origin: addr,
Type: HostTypeIP,
}
for i := 0; i < math.MaxInt; i++ {
if i%2 == 0 {
lowIP = NextIP(lowIP, false)
hostChan <- Host{
IP: lowIP,
Origin: lowIP.String(),
Type: HostTypeIP,
}
} else {
highIP = NextIP(highIP, true)
hostChan <- Host{
IP: highIP,
Origin: highIP.String(),
Type: HostTypeIP,
}
}
}
}()
return hostChan
}
func LookupIP(addr string) (net.IP, error) {
ips, err := net.LookupIP(addr)
if err != nil {
return nil, fmt.Errorf("failed to lookup: %w", err)
}
var arr []net.IP
for _, ip := range ips {
if ip.To4() != nil || enableIPv6 {
arr = append(arr, ip)
}
}
if len(arr) == 0 {
return nil, errors.New("no IP found")
}
return arr[0], nil
}
func RemoveDuplicateStr(strSlice []string) []string {
allKeys := make(map[string]bool)
var list []string
@@ -128,3 +192,17 @@ func OutWriter(writer io.Writer) chan<- string {
}()
return ch
}
func NextIP(ip net.IP, increment bool) net.IP {
// Convert to big.Int and increment
ipb := big.NewInt(0).SetBytes(ip)
if increment {
ipb.Add(ipb, big.NewInt(1))
} else {
ipb.Sub(ipb, big.NewInt(1))
}
// Add leading zeros
b := ipb.Bytes()
b = append(make([]byte, len(ip)-len(b)), b...)
return b
}