Fix: let lib/traceroute wait all goroutine finish

This commit is contained in:
2022-05-05 20:50:28 +08:00
parent e4af31660d
commit 0d2e6e1e17
3 changed files with 36 additions and 14 deletions

View File

@ -20,6 +20,9 @@ import (
"github.com/oschwald/maxminddb-golang"
)
var isFinish bool = false
var destIP net.IP
func remove(slice []string, s int) []string {
if s < len(slice) {
return append(slice[:s], slice[s+1:]...)
@ -27,6 +30,15 @@ func remove(slice []string, s int) []string {
return slice
}
func removeEmpty(slice []string) (ret []string) {
for i := 0; i < len(slice); i++ {
if (len(slice[i])) != 0 {
ret = append(ret, slice[i])
}
}
return
}
type record struct {
ASN int `maxminddb:"autonomous_system_number"`
ASO string `maxminddb:"autonomous_system_organization"`
@ -88,7 +100,7 @@ func parseIPFromMap42(ip net.IP) (record, APIResponse, error) {
APIResponse := APIResponse{
Code: 0,
Detail: IPDetail{
ISP: strings.Join(remove(remove(strings.Split(res.Area, "\t"), 6), 5), " "),
ISP: strings.Join(removeEmpty(remove(remove(strings.Split(res.Area, "\t"), 6), 5)), " "),
},
}
return record, APIResponse, nil
@ -150,7 +162,8 @@ func printHop(hop traceroute.TracerouteHop) {
if _, Prefix, _ := net.ParseCIDR("172.16.0.0/12"); Prefix.Contains(ip) {
info, APIResponse, err = parseIPFromMap42(ip)
if err != nil {
log.Fatal(err)
info = parseIPFromMaxminddb(ip)
APIResponse = parseIPFromBilibiliAPI(ip)
}
} else {
info = parseIPFromMaxminddb(ip)
@ -172,9 +185,9 @@ func printHop(hop traceroute.TracerouteHop) {
ASN = fmt.Sprintf("AS%v", info.ASN)
}
if APIResponse.Code != 0 {
fmt.Printf("%-3d %8v %15v (%v) %8v\n", hop.TTL, ASN, hostOrAddr, addr, hop.ElapsedTime.Round(time.Microsecond))
fmt.Printf("%-3d %8v %15v %18v %8v\n", hop.TTL, ASN, hostOrAddr, "("+addr+")", hop.ElapsedTime.Round(time.Microsecond))
} else {
fmt.Printf("%-3d %8v %15v (%v) %8v ", hop.TTL, ASN, hostOrAddr, addr, hop.ElapsedTime.Round(time.Microsecond))
fmt.Printf("%-3d %8v %15v %18v %8v ", hop.TTL, ASN, hostOrAddr, "("+addr+")", hop.ElapsedTime.Round(time.Microsecond))
var flag bool = false
@ -211,6 +224,11 @@ func printHop(hop traceroute.TracerouteHop) {
} else {
fmt.Printf("%-3d *\n", hop.TTL)
}
if destIP.Equal(ip) {
isFinish = true
}
}
func address(address [4]byte) string {
@ -237,6 +255,7 @@ func main() {
fmt.Printf("traceroute to %v (%v), %v hops max, %v byte packets, using ICMP methods.\n", host, ipAddr, options.MaxHops(), options.PacketSize())
c := make(chan traceroute.TracerouteHop, 0)
d := make(chan bool)
go func() {
for {
hop, ok := <-c
@ -245,14 +264,14 @@ func main() {
return
}
printHop(hop)
d <- true
}
}()
res, err := traceroute.Traceroute(ipAddr.String(), &options, c)
destIP = ipAddr.IP
_, err = traceroute.Traceroute(ipAddr.String(), &options, d, c)
if err != nil {
fmt.Printf("Error: %v", err)
}
printHop(res.Hops[len(res.Hops)-1])
}