原理: 采用多线程的方式实现ping命令,然后将ping命令的结果存放在文件中,扫描文件中成功和失败的关键字,然后确定ping命令是否成功,然后得出结果。打印在控制台上。
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
char file[300][100] = {};// 记录命令ping -r -2 192.168.0.2等 > 192.168.0.2.txt
char addr[300][100] = {};// 记录文件路径
int begin = 1,end = 255;
int pos[300];
int sum = 0;
int tt[300];
void input(){
printf("please input the range\n");
scanf("%d %d",&begin,&end);
while(begin <= 0 || begin >= 256 || end <= 0 || end >= 256 && begin > end){
printf("please input the range\n");
scanf("%d %d",&begin,&end);
}
}
void *f_ping(void *p){
int pp = *(int *)p;
system(file[pp]);
int fd = open(addr[pp],O_RDWR);
if(fd == -1){printf("error on 192.168.0.%d\n",pp);return ;}
char ch;
int flag = 0;
while(read(fd,&ch,sizeof(ch)) != 0){
if(ch == 'U'){
flag = 1;
break;
}
}
if(!flag){
tt[pp] = 1;
sum++;
}
remove(addr[pp]);
}
void sweep(){
int i;
for(i = begin; i <= end; ++i){
sprintf(file[i],"ping -c 2 192.168.0.%d > %d.txt",i,i);
sprintf(addr[i],"%d.txt",i);
pthread_t key;
pos[i] = i;
pthread_create(&key,0,f_ping,pos + i);
}
}
int main(void){
input();
sweep();
sleep(1);
getchar();
getchar();
int i;
printf("there are %d.\n",sum);
for(i = begin; i < end; ++i){
if(tt[i] == 1)printf("192.168.0.%d is ok\n",i);
}
return 0;
}

本文介绍了一种使用多线程实现Ping命令扫描的方法,并通过文件读取结果来判断主机是否可达。该程序能够批量测试指定IP范围内的主机连通性。

被折叠的 条评论
为什么被折叠?



