go实现fping功能
1、什么是fping
fping是一个类似ping的程序,与ping不同的是你可以同时指定多个要ping的目标。
fping发送完ping包后不等待回应,而是继续下一个目标
3、具体实现
1.获取IP段
//IP段 '1','2020-11-2617:11:39.515','2020-11-2617:11:39.515','1.0.1.0','1.0.3.255','福建','电信' '2','2020-11-2617:11:43.553','2020-11-2617:11:43.553','1.0.8.0','1.0.15.255','广东','电信' '3','2020-11-2617:11:47.563','2020-11-2617:11:47.563','1.0.32.0','1.0.63.255','广东','电信' '4','2020-11-2617:11:53.621','2020-11-2617:11:53.621','1.1.0.0','1.1.0.255','福建','电信' '5','2020-11-2617:11:57.635','2020-11-2617:11:57.635','1.1.2.0','1.1.7.255','福建','电信' '6','2020-11-2617:11:59.642','2020-11-2617:11:59.642','1.1.8.0','1.1.63.255','广东','电信' '7','2020-11-2617:12:05.671','2020-11-2617:12:05.671','1.2.0.0','1.2.1.255','福建','电信' '8','2020-11-2617:12:07.674','2020-11-2617:12:07.674','1.2.2.0','1.2.2.255','北京','联通' '9','2020-11-2617:12:13.690','2020-11-2617:12:13.690','1.2.5.0','1.2.7.255','北京','电信'
2.ping方法(单个,多个已给出)
//单个ping //IsAlivePing:检测目标IP是否能够ping通,target为目标IP funcIsAlivePing(targetstring)(bool,error){ pinger,err:=ping.NewPinger(target) iferr!=nil{ returnfalse,err } pinger.Count=10 PINGTIME:=time.Duration(1000) pinger.Timeout=time.Duration(PINGTIME*time.Millisecond) pinger.SetPrivileged(true)//选择icmp,不选择udp pinger.Run() stats:=pinger.Statistics() //判断是否有接收到的包 ifstats.PacketsRecv>=1{ returntrue,nil } returnfalse,nil } //多个ping:得到死IP //FilterActiveIPs:过滤活IP,筛选出死IP funcFilterActiveIPs(ips[]string)(inactiveIPs[]string){ varlocksync.Mutex varwgsync.WaitGroup wg.Add(len(ips)) for_,ip:=rangeips{ gofunc(ipstring){ deferwg.Done() //判断是死ip,并且格式正确 isAlive,err:=IsAlivePing(ip) if!isAlive&&err==nil{ RandomSleep(2)//睡眠[1,2]秒,二次确认是否为死IP ifisAlive,_:=IsAlivePing(ip);!isAlive{ RandomSleep(2)//再睡眠[1,2]秒,三次确认是否为死IP ifisAlive,_:=IsAlivePing(ip);!isAlive{ lock.Lock() deferlock.Unlock() inactiveIPs=append(inactiveIPs,ip) } } } }(ip) } wg.Wait() returninactiveIPs } //多个ping:得到活IP //FilterInactiveIPs:过滤死IP,筛选出活IP funcFilterInactiveIPs(ips[]string)(activeIPs[]string){ varlocksync.Mutex varwgsync.WaitGroup wg.Add(len(ips)) for_,ip:=rangeips{ gofunc(ipstring){ deferwg.Done() //判断是活ip,并且格式正确 ifisAlive,err:=IsAlivePing(ip);isAlive&&err==nil{ lock.Lock() deferlock.Unlock() activeIPs=append(activeIPs,ip) } }(ip) } wg.Wait() returnactiveIPs } //RandomSleep:随机睡眠[1,t]秒 funcRandomSleep(tint){ rand.Seed(time.Now().UnixNano()) r:=time.Duration(rand.Intn(t)+1) time.Sleep(r*time.Second) }
3.分解IP段
//Separation:分解IP段 func(i*impl)Separation(minIP,maxIPstring)[]string{ shouldStrs:=make([]string,0)//这是IP段的所有IP //fori:=0;imath.MaxUint32{ return"",errors.New("beyondthescopeofipv4") } ip:=make(net.IP,net.IPv4len) ip[0]=byte(i>>24) ip[1]=byte(i>>16) ip[2]=byte(i>>8) ip[3]=byte(i) returnip.String(),nil } //IPString2Long把ip字符串转为数值 funcIPString2Long(ipstring)(uint,error){ b:=net.ParseIP(ip).To4() ifb==nil{ return0,errors.New("invalidipv4format") } returnuint(b[3])|uint(b[2])<<8|uint(b[1])<<16|uint(b[0])<<24,nil }
到此这篇关于go实现fping功能的文章就介绍到这了,更多相关go实现fping内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!