Last active
June 30, 2023 06:26
-
-
Save flxxyz/b7ec986055f06269960c1bdf7af66bec to your computer and use it in GitHub Desktop.
IPv4, IPv6 network support check(检查IPv4, IPv6网络支持)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"os/exec" | |
"runtime" | |
"strconv" | |
"time" | |
) | |
const ( | |
DnsIPv4 = "1.1.1.1" // Cloudflare DNS | |
DnsIPv6 = "2606:4700:4700::1111" // Cloudflare DNS | |
) | |
type IPvNSupport struct { | |
DnsIPv4 string | |
DnsIPv6 string | |
CheckTiming time.Duration | |
Count int | |
ipv4Support chan bool | |
ipv6Support chan bool | |
} | |
type Result struct { | |
ipv4 <-chan bool | |
ipv6 <-chan bool | |
} | |
func (s *IPvNSupport) command(enableIPv6 bool) (string, []string) { | |
pingCommand := "ping" | |
pingCommandArgs := []string{"-4", s.DnsIPv4, "-c", strconv.Itoa(s.Count)} | |
if enableIPv6 { | |
pingCommandArgs[0] = "-6" | |
pingCommandArgs[1] = s.DnsIPv6 | |
} | |
if runtime.GOOS == "windows" { | |
pingCommandArgs[2] = "-n" | |
} else { | |
if runtime.GOOS == "darwin" { | |
if enableIPv6 { | |
pingCommand = "ping6" | |
} | |
pingCommandArgs = append(pingCommandArgs[:0], pingCommandArgs[1:]...) | |
} | |
} | |
return pingCommand, pingCommandArgs | |
} | |
func (s *IPvNSupport) check(enableIPv6 bool) { | |
for { | |
pingCommand, pingCommandArgs := s.command(enableIPv6) | |
ping := exec.Command(pingCommand, pingCommandArgs...) | |
startup := time.Now() | |
if enableIPv6 { | |
s.ipv6Support <- ping.Run() == nil | |
} else { | |
s.ipv4Support <- ping.Run() == nil | |
} | |
diff := time.Now().Sub(startup) | |
if diff < s.CheckTiming { | |
time.Sleep(s.CheckTiming - diff) | |
} | |
} | |
} | |
func (s *IPvNSupport) CheckIPv4() { | |
enableIPv6 := false | |
go s.check(enableIPv6) | |
} | |
func (s *IPvNSupport) CheckIPv6() { | |
enableIPv6 := true | |
go s.check(enableIPv6) | |
} | |
func (s *IPvNSupport) Result() *Result { | |
return &Result{ipv4: s.ipv4Support, ipv6: s.ipv6Support} | |
} | |
func (s *IPvNSupport) Run() *Result { | |
s.CheckIPv4() | |
s.CheckIPv6() | |
return s.Result() | |
} | |
func NewIPvNSupport() *IPvNSupport { | |
ip := &IPvNSupport{} | |
ip.DnsIPv4 = DnsIPv4 | |
ip.DnsIPv6 = DnsIPv6 | |
ip.CheckTiming = time.Second * 12 | |
ip.Count = 10 | |
ip.ipv4Support = make(chan bool) | |
ip.ipv6Support = make(chan bool) | |
return ip | |
} | |
func main() { | |
ipvNSupport := NewIPvNSupport() | |
result := ipvNSupport.Run() | |
for { | |
select { | |
case ack := <-result.ipv4: | |
log.Println("IPv4Support:", ack) | |
case ack := <-result.ipv6: | |
log.Println("IPv6Support:", ack) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment