func PortCollect(p *model.PortCollect) {
value := 0
if isListening(p.Port) {
value = 1
}python
item := core.GaugeValue("proc.port.listen", value, p.Tags)
item.Step = int64(p.Step)
item.Timestamp = time.Now().Unix()
item.Endpoint = identity.Identity
core.Push([]*dataobj.MetricValue{item})
}linux
func isListening(port int) bool {
tcpAddress, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf(":%v", port))
if err != nil {
logger.Errorf("net.ResolveTCPAddr(tcp4, :%v) fail: %v", port, err)
return false
}服務器
listener, err := net.ListenTCP("tcp", tcpAddress)
if err != nil {
logger.Debugf("cannot listen :%v(%v), so we think :%v is already listening", port, err, port)
return true
}
listener.Close()socket
return false
}tcp
func isListen(port, timeout int, ip string) bool {
var conn net.Conn
var err error
addr := fmt.Sprintf("%s:%d", ip, port)
if timeout <= 0 {
// default timeout 3 second
timeout = 3
}
conn, err = net.DialTimeout("tcp", addr, time.Duration(timeout)*time.Second)
if err != nil {
return false
}
conn.Close()
return true
}ide
用isListen函數去檢測端口存活
func GetLocalIp() (result string) {
addrs, err := net.InterfaceAddrs()
result="127.0.0.1"
if err != nil{
fmt.Println(err)
return result
}
for _, value := range addrs{
if ipnet, ok := value.(*net.IPNet); ok && !ipnet.IP.IsLoopback(){
if ipnet.IP.To4() != nil{
result=ipnet.IP.String()
return result
}
}
}
return result
}函數
func PortCollect(p *model.PortCollect) {
value := 0
local_ip := GetLocalIp()
if isListen(p.Port, 1, "127.0.0.1") {
value = 1
} else if isListen(p.Port, 1, local_ip) {
value = 1
} else if isListen(p.Port, 1, "::1") {
value = 1
}oop
item := core.GaugeValue("proc.port.listen", value, p.Tags)
item.Step = int64(p.Step)
item.Timestamp = time.Now().Unix()
item.Endpoint = identity.Identity
core.Push([]*dataobj.MetricValue{item})
}ui
在此仍是要感謝滴滴的大佬們的解惑!spa