1
0
mirror of https://github.com/taigrr/go-fastping synced 2025-01-18 05:03:15 -08:00

Fix setting IPv6 source address

This commit is contained in:
Anton Skorokhod 2015-08-17 19:56:48 +02:00 committed by Tatsushi Demachi
parent a06009512e
commit 716eadcd8f

View File

@ -131,6 +131,7 @@ type Pinger struct {
addrs map[string]*net.IPAddr addrs map[string]*net.IPAddr
network string network string
source string source string
source6 string
hasIPv4 bool hasIPv4 bool
hasIPv6 bool hasIPv6 bool
ctx *context ctx *context
@ -160,6 +161,7 @@ func NewPinger() *Pinger {
addrs: make(map[string]*net.IPAddr), addrs: make(map[string]*net.IPAddr),
network: "ip", network: "ip",
source: "", source: "",
source6: "",
hasIPv4: false, hasIPv4: false,
hasIPv6: false, hasIPv6: false,
Size: TimeSliceLength, Size: TimeSliceLength,
@ -187,25 +189,36 @@ func (p *Pinger) Network(network string) (string, error) {
return origNet, nil return origNet, nil
} }
// Source sets source IP for sending ICMP packets and returns the previous // Source sets ipv4/ipv6 source IP for sending ICMP packets and returns the previous
// setting. Empty value indicates to use system default one. // setting. Empty value indicates to use system default one (for both ipv4 and ipv6).
func (p *Pinger) Source(source string) (string, error) { func (p *Pinger) Source(source string) (string, error) {
// using ipv4 previous value for new empty one
origSource := p.source origSource := p.source
if "" == source { if "" == source {
p.mu.Lock() p.mu.Lock()
p.source = source p.source = ""
p.source6 = ""
p.mu.Unlock() p.mu.Unlock()
return origSource, nil return origSource, nil
} }
addr := net.ParseIP(source) addr := net.ParseIP(source)
if addr == nil { if addr == nil {
return origSource, errors.New(source + " is not a valid textual representation of an IP address") return origSource, errors.New(source + " is not a valid textual representation of an IPv4/IPv6 address")
} }
if isIPv4(addr) {
p.mu.Lock() p.mu.Lock()
p.source = source p.source = source
p.mu.Unlock() p.mu.Unlock()
} else if isIPv6(addr) {
origSource = p.source6
p.mu.Lock()
p.source6 = source
p.mu.Unlock()
} else {
return origSource, errors.New(source + " is not a valid textual representation of an IPv4/IPv6 address")
}
return origSource, nil return origSource, nil
} }
@ -396,7 +409,7 @@ func (p *Pinger) run(once bool) {
} }
if p.hasIPv6 { if p.hasIPv6 {
if conn6 = p.listen(ipv6Proto[p.network], p.source); conn6 == nil { if conn6 = p.listen(ipv6Proto[p.network], p.source6); conn6 == nil {
return return
} }
defer conn6.Close() defer conn6.Close()