读取文本文件中的IP,然后测试能否ping通
其实原理非常简单,这里只是写了一个demo,后期可以任意扩展成自己想要的样子,
先说判断依据:
这里ping 1.1的时候是通的,ping 1.2的时候是不通的,很明显返回的输出信息不同,我这里只是使用简单的返回显示的字的数量作为依据,判断通还是不通。
使用一个多线程,如果文本文件中的ip比较多,单线程处理起来会变得很慢,但是并没有限制线程创建的数量,如果数量太多肯定会导致程序奔溃,下面给出一个参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdlib.h>
int flag_end = 0;
//执行线程的一个函数
void *do_thread(void *arg)
{
int num = 0;
char ping_buf[160];
char psBuffer[512];
FILE *pPipe;
//printf("%s\n", ip);
sprintf(ping_buf,"ping -n 1 %s",(char *)arg);
flag_end = 0;
if((pPipe = _popen(ping_buf,"rt")) == NULL )
exit( 1 );
while(fgets(psBuffer, 512, pPipe))
{
//printf("%s\n", psBuffer);
//printf("strlenpsBuffer = %d\n", strlen(psBuffer));
num += strlen(psBuffer);
}
if(num > 200){
printf("%s OK\n", ping_buf);
}else{
printf("%s NO\n", ping_buf);
}
num = 0;
_pclose(pPipe);
}
int main()
{
pthread_t tid;
char ip[200];
FILE *fp;
int ret;
fp = fopen("d:\\1.txt", "r+");//“r+”
if (fp == NULL)
{
printf("Cannot open the file!\n");
exit(0);
}
while (!feof(fp))
{
if(flag_end == 0){
fscanf(fp, "%s", ip);
//printf("--------%s\n", ip);
#if 1
ret = pthread_create(&tid , NULL , do_thread , ip);
if(ret != 0)
{
fprintf(stderr , "创建线程失败!\n");
return -1 ;
}
//当线程结束时自动释放id号
ret = pthread_detach(tid);
flag_end = 1;
#endif
}
Sleep(20);//休眠20毫秒
//getchar();
}
fclose(fp);
getchar();
return 0;
}
运行效果:
文本文件中的ip: