📄 nat.c
字号:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netinet/ip.h>#include <arpa/inet.h>#include <sys/time.h>int create_raw_socket(void);int send_frag_ip_pkt(int);u_short in_cksum(u_short *, int);static u_short ip_id = 0x789;static char *dst_addr = "1.1.1.1";int main(int argc, char *argv[]){ int sock = create_raw_socket(); int n = 0; if(argc>=2) { dst_addr = argv[1]; } srand(time(NULL)); while(1) { printf("%d: Sending IP packet ... ", n++); fflush(stdout); if(send_frag_ip_pkt(sock)<0) { perror("sendto"); return -1; } printf("done\n");/* if( (n%1256)==0 ) sleep(1);*/ } close(sock); return 0;}int create_raw_socket(void){ int sock; int on = 1; sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if(sock<0) { perror("socket"); exit(1); } if(setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on))<0) { perror("setsockopt"); exit(1); } return sock;}int send_frag_ip_pkt(int sd){ struct sockaddr_in sin; char buf[256]; char local_addr[32]; struct iphdr *iph; u_short *port; sin.sin_family = AF_INET; sin.sin_addr.s_addr = inet_addr(dst_addr); sin.sin_port = 0; sprintf(local_addr, "192.168.0.%u", 1 + ((unsigned)rand())%253 ); iph = (struct iphdr *)buf; iph->ihl = 5; iph->version = 4; iph->tos = 0; iph->tot_len = sizeof(buf); iph->id = ip_id++; iph->frag_off = htons(IP_MF); iph->ttl = 255; iph->protocol = IPPROTO_TCP; iph->check = 0; iph->saddr = inet_addr(local_addr); iph->daddr = inet_addr(dst_addr); iph->check = in_cksum((u_short *)buf, 20); port = (u_short *)(buf + sizeof(struct iphdr)); *port = (u_short)rand(); port ++; *port = (u_short)rand(); return sendto(sd, buf, sizeof(buf), 0, (struct sockaddr *)&sin, sizeof(sin));}u_short in_cksum(u_short *addr, int len){ int nleft = len; int sum = 0; u_short *w = addr; u_short answer = 0; while(nleft > 1) { sum += *w; 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;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -