1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#define PACKET_SIZE 4096
using namespace std;
int dPort;
char dIP[sizeof "255.255.255.255"];
char data[PACKET_SIZE];
sockaddr_in sin;
struct iphdr *iph = (struct iphdr *) data;
struct tcphdr *tcph = (struct tcphdr *) (data + sizeof (struct ip));
char sIP[sizeof "255.255.255.255"];
int sPort = 0;
unsigned short csum(unsigned short*, int);
int main(int argc, char** argv) {
int sClient = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);
if(sClient < 0) {
cout << "Error: " << errno << endl;
return -1;
}
dPort = 25565;
sprintf(dIP, "192.168.121.50");
sin.sin_family = AF_INET;
sin.sin_port = dPort;
sin.sin_addr.s_addr = inet_addr(dIP);
memset(data, 0, PACKET_SIZE);
srand(time(0));
snprintf(sIP, 16, "%lu.%lu.%lu.%lu", random() % 255, random() % 255, random() % 255, random() % 255);
sPort = random() % 5000;
iph->ihl = 5;
iph->version = 4;
iph->tos = 0;
iph->tot_len = htonl(sizeof(struct iphdr) + sizeof(struct tcphdr));
iph->id = htons(54321);
iph->frag_off = 0;
iph->ttl = MAXTTL;
iph->protocol = IPPROTO_TCP;
iph->check = 0;
iph->saddr = inet_addr(sIP);
iph->daddr = sin.sin_addr.s_addr;
iph->check = csum((unsigned short *) data, iph->tot_len >> 1);
tcph->source = htons(sPort);
tcph->seq = random();
tcph->ack_seq = 0;
tcph->res2 = 0;
tcph->doff = 5;
tcph->syn = 1;
tcph->window = htonl(65535);
tcph->check = 0;
tcph->urg_ptr = 0;
tcph->dest = htons(dPort);
tcph->check = 0;
int tmp = 1;
const int* val = &tmp;
if(setsockopt(sClient, IPPROTO_IP, IP_HDRINCL, val, sizeof(tmp)) < 0) {
cout << "Error: " << errno << endl;
return -1;
}
if(sendto(sClient, data, iph->tot_len, 0, (sockaddr*)&sin, sizeof(sin)) < 0) {
cout << "Error: " << errno << endl;
return -1;
} else {
cout << "Packet sent from " << sIP << ":" << sPort << " to " << dIP << ":" << dPort << endl;
}
shutdown(sClient, SHUT_WR);
return 0;
}
unsigned short csum(unsigned short *buf, int nWords) {
unsigned long sum;
for(sum = 0; nWords > 0; nWords--)
sum += *buf++;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
|