1. 程式人生 > >區域網ip掃描器c語言多執行緒 linux版

區域網ip掃描器c語言多執行緒 linux版

原理: 採用多執行緒的方式實現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;
}