ping: Fix missing TTL and ICMP error handling

This commit is contained in:
世界 2026-06-22 16:16:12 +08:00
parent 3a09076491
commit 1251022fce
No known key found for this signature in database
GPG key ID: CD109927C34A63C4
5 changed files with 153 additions and 60 deletions

View file

@ -1,30 +1,29 @@
package ping
import (
"context"
"net"
"net/netip"
"syscall"
"github.com/sagernet/sing/common/bufio"
"github.com/sagernet/sing/common/control"
M "github.com/sagernet/sing/common/metadata"
"golang.org/x/sys/windows"
)
func connect(privileged bool, controlFunc control.Func, destination netip.Addr) (net.Conn, error) {
var dialer net.Dialer
dialer.Control = controlFunc
var listenConfig net.ListenConfig
listenConfig.Control = controlFunc
if destination.Is6() {
dialer.Control = control.Append(dialer.Control, func(network, address string, conn syscall.RawConn) error {
listenConfig.Control = control.Append(listenConfig.Control, func(network, address string, conn syscall.RawConn) error {
return control.Raw(conn, func(fd uintptr) error {
err := windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IPV6_HOPLIMIT, 1)
if err != nil {
return err
}
err = windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IPV6_RECVTCLASS, 1)
if err != nil {
return err
}
return nil
return windows.SetsockoptInt(windows.Handle(fd), windows.IPPROTO_IPV6, IPV6_RECVTCLASS, 1)
})
})
}
@ -34,5 +33,11 @@ func connect(privileged bool, controlFunc control.Func, destination netip.Addr)
} else {
network = "ip6:ipv6-icmp"
}
return dialer.Dial(network, destination.String())
// A connected raw socket only receives messages from the connected peer, so transit routers'
// Time Exceeded replies needed by traceroute never arrive.
packetConn, err := listenConfig.ListenPacket(context.Background(), network, "")
if err != nil {
return nil, err
}
return bufio.NewBindPacketConn(packetConn, M.SocksaddrFrom(destination, 0).IPAddr()), nil
}