Add ability to set outgouing interface (only Linux support). Review

This commit is contained in:
TimofeyAf 2022-02-22 23:49:57 +03:00
parent 3ef8b51873
commit 72dfce2120
4 changed files with 5 additions and 38 deletions

View File

@ -1,11 +1,8 @@
package ping
import (
"errors"
"net"
"reflect"
"runtime"
"syscall"
"time"
"golang.org/x/net/icmp"
@ -41,38 +38,6 @@ func (c *icmpConn) SetReadDeadline(t time.Time) error {
return c.c.SetReadDeadline(t)
}
func getConnFD(conn *icmp.PacketConn) (fd int) {
var packetConn reflect.Value
defer func() {
if r := recover(); r != nil {
fd = -1
}
}()
if conn.IPv4PacketConn() != nil {
packetConn = reflect.ValueOf(conn.IPv4PacketConn().PacketConn)
} else if conn.IPv6PacketConn() != nil {
packetConn = reflect.ValueOf(conn.IPv6PacketConn().PacketConn)
} else {
return -1
}
netFD := reflect.Indirect(reflect.Indirect(packetConn).FieldByName("fd"))
pollFD := netFD.FieldByName("pfd")
systemFD := pollFD.FieldByName("Sysfd")
return int(systemFD.Int())
}
func (c *icmpConn) BindToDevice(ifName string) error {
if runtime.GOOS == "linux" {
if fd := getConnFD(c.c); fd >= 0 {
return syscall.BindToDevice(fd, ifName)
}
}
return errors.New("bind to interface unsupported") // FIXME: or nil
}
func (c *icmpConn) WriteTo(b []byte, dst net.Addr) (int, error) {
if c.c.IPv6PacketConn() != nil {
if err := c.c.IPv6PacketConn().SetHopLimit(c.ttl); err != nil {

View File

@ -1,4 +1,4 @@
//go:build linux
// +build linux
package ping

View File

@ -1,7 +1,9 @@
//go:build !linux && !windows
// +build !linux,!windows
package ping
import "errors"
// Returns the length of an ICMP message.
func (p *Pinger) getMessageLength() int {
return p.Size + 8

View File

@ -1,4 +1,4 @@
//go:build windows
// +build windows
package ping