refactor the code related to xtcp (#3449)

This commit is contained in:
fatedier
2023-05-28 16:50:43 +08:00
committed by GitHub
parent 9f029e3248
commit c71efde303
44 changed files with 3305 additions and 1699 deletions

View File

@@ -16,6 +16,7 @@ package nathole
import (
"bytes"
"fmt"
"net"
"strconv"
@@ -63,3 +64,49 @@ func (s *ChangedAddress) GetFrom(m *stun.Message) error {
func (s *ChangedAddress) String() string {
return net.JoinHostPort(s.IP.String(), strconv.Itoa(s.Port))
}
func ListAllLocalIPs() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
ips := make([]net.IP, 0, len(addrs))
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
ips = append(ips, ip)
}
return ips, nil
}
func ListLocalIPsForNatHole(max int) ([]string, error) {
if max <= 0 {
return nil, fmt.Errorf("max must be greater than 0")
}
ips, err := ListAllLocalIPs()
if err != nil {
return nil, err
}
filtered := make([]string, 0, max)
for _, ip := range ips {
if len(filtered) >= max {
break
}
// ignore ipv6 address
if ip.To4() == nil {
continue
}
// ignore localhost IP
if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
continue
}
filtered = append(filtered, ip.String())
}
return filtered, nil
}