github.com/nxtrace/NTrace-core@v1.3.1-0.20240513132635-39169291e8c9/trace/temp_printer.go (about)

     1  package trace
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/nxtrace/NTrace-core/ipgeo"
     8  )
     9  
    10  func HopPrinter(h Hop) {
    11  	if h.Address == nil {
    12  		fmt.Println("\t*")
    13  	} else {
    14  		txt := "\t"
    15  
    16  		if h.Hostname == "" {
    17  			txt += fmt.Sprint(h.Address, " ", fmt.Sprintf("%.2f", h.RTT.Seconds()*1000), "ms")
    18  		} else {
    19  			txt += fmt.Sprint(h.Hostname, " (", h.Address, ") ", fmt.Sprintf("%.2f", h.RTT.Seconds()*1000), "ms")
    20  		}
    21  
    22  		if h.Geo != nil {
    23  			txt += " " + formatIpGeoData(h.Address.String(), h.Geo)
    24  		}
    25  
    26  		fmt.Println(txt)
    27  	}
    28  }
    29  
    30  func formatIpGeoData(ip string, data *ipgeo.IPGeoData) string {
    31  	var res = make([]string, 0, 10)
    32  
    33  	if data.Asnumber == "" {
    34  		res = append(res, "*")
    35  	} else {
    36  		res = append(res, "AS"+data.Asnumber)
    37  	}
    38  
    39  	// TODO: 判断阿里云和腾讯云内网,数据不足,有待进一步完善
    40  	// TODO: 移动IDC判断到Hop.fetchIPData函数,减少API调用
    41  	if strings.HasPrefix(ip, "9.") {
    42  		res = append(res, "LAN Address", "")
    43  	} else if strings.HasPrefix(ip, "11.") {
    44  		res = append(res, "LAN Address", "")
    45  	} else if data.Country == "" {
    46  		res = append(res, "LAN Address")
    47  	} else {
    48  		// 有些IP的归属信息为空,这个时候将ISP的信息填入
    49  		if data.Owner == "" {
    50  			data.Owner = data.Isp
    51  		}
    52  		if data.District != "" {
    53  			data.City = data.City + ", " + data.District
    54  		}
    55  		if data.Prov == "" && data.City == "" {
    56  			// anyCast或是骨干网数据不应该有国家信息
    57  			data.Owner = data.Owner + ", " + data.Owner
    58  		} else {
    59  			// 非骨干网正常填入IP的国家信息数据
    60  			res = append(res, data.Country)
    61  		}
    62  
    63  		if data.Prov != "" {
    64  			res = append(res, data.Prov)
    65  		}
    66  		if data.City != "" {
    67  			res = append(res, data.City)
    68  		}
    69  
    70  		if data.Owner != "" {
    71  			res = append(res, data.Owner)
    72  		}
    73  	}
    74  
    75  	return strings.Join(res, ", ")
    76  }