日期:2014-05-16 浏览次数:20741 次
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<netdb.h> #include<unistd.h> #include<sys/time.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in_systm.h> #include<netinet/in.h> #include<netinet/ip.h> #include<netinet/ip_icmp.h> #include<arpa/inet.h> #include <time.h> /*#define CHKADDRESS( _saddr_) { u_char *p =(char *)&(_saddr_); if( (p[0] == 10) || (p[0] ==168 &&16<=p[1]&&p[1]<=31) ||(p[0] ==192 && p[1]==168) {} else { fprintf(stderr,"IP address error.\n"); exit(EXIT_FAILURE); } }*/ enum {CMD_NAME,DST_IP,START_PORT,LAST_PORT}; #define MAXBUFF 8192 int main(int argc,char *argv[]) { clock_t start, finish; struct icmp *icmp; fd_set select_fd; struct sockaddr_in send_sa; int recv_sd; int send_sd; char buff[MAXBUFF]; int endport; int startport; int dstport; struct timeval tv; struct ip *ip; int hlen,port; int count; if(argc!=4) { fprintf(stderr," usge:%s dst_ip start_port last_port\n",argv[CMD_NAME]); exit(EXIT_FAILURE); } send_sa.sin_family = AF_INET; send_sa.sin_addr.s_addr = inet_addr(argv[DST_IP]); startport = atoi(argv[START_PORT]); endport = atoi(argv[LAST_PORT]); //CHKADDRESS(send_sa.sin_addr.s_addr); if( (send_sd = socket(AF_INET,SOCK_DGRAM,0))<0) { perror(" socket (SOCK_DGRAM)"); exit(EXIT_FAILURE); } if( (recv_sd = socket(AF_INET,SOCK_RAW,IPPROTO_ICMP))<0) { perror(" socket (SOCK_RAW)"); exit(EXIT_FAILURE); } for(dstport = startport;dstport<=endport;dstport++) { printf(" Scan port %d: %d times\r",dstport,count); fflush(stdout); send_sa.sin_port = htons (dstport); sendto(send_sd,NULL,0,0,(void *) &send_sa,sizeof(send_sa)); tv.tv_sec=1; tv.tv_usec=0; count=0; //记录每次同一端口,ICMP包数量 start = clock(); while(1) { FD_ZERO(&select_fd); FD_SET(recv_sd,&select_fd); if(select (recv_sd+1,&select_fd,NULL,NULL,&tv)>0) if(recvfrom(recv_sd,buff,MAXBUFF,0,NULL,NULL)!=56) //ICMP包,长度为56,IP+ICMP+IP+UDP continue; //intf("a new icmp ack\n"); if( ((finish=clock() )-start)>=2) { printf("2 sec no target icmp ack.\n"); struct servent *se_t; se_t=getservbyport(htons (dstport)," udp"); printf("%5d %-20s\n",dstport,(se_t==NULL)?"unkown":se_t->s_name); break; } ip=(struct ip *)buff; hlen=ip->ip_hl<<2; icmp=(struct icmp *)(buff+hlen); port=ntohs(* (u_short *)(buff+20+8+20+2) ); if( (ip->ip_src.s_addr!=send_sa.sin_addr.s_addr) || (icmp->icmp_type!=ICMP_UNREACH) || (icmp->icmp_code!=ICMP_UNREACH_PORT) ||(port!=dstport)) { if(count>10) { printf("port %d:icmp_type is %d;icmp_code is %d.\n",port,icmp->icmp_type,icmp->icmp_code); break; } if(ip->ip_src.s_addr==send_sa.sin_addr.s_addr && port==dstport) { //printf(" %d times\r",count); count++; break; }