#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#define DEST_PROT (4000)
#define PACKET_LEN (128)
#define TTLVAL (255)
void ip_packet_ctor (struct ip *iphdr , struct sockaddr_in *dest)
{
int ip_len = sizeof(struct ip) + sizeof(struct tcphdr);
iphdr->ip_v = IPVERSION;
iphdr->ip_hl = sizeof(struct ip) >> 2;
iphdr->ip_tos = 0;
iphdr->ip_len = htons(ip_len);
iphdr->ip_id = 0;
iphdr->ip_off = 0;
iphdr->ip_ttl = TTLVAL;
iphdr->ip_p = IPPROTO_TCP;
iphdr->ip_sum = 0;
iphdr->ip_dst.s_addr = dest->sin_addr.s_addr;
}
void tcp_packet_ctor (struct tcphdr *tcphdr, u16_t srcprot, struct socka ddr_in *dest)
{
tcphdr->th_sport = htons(srcprot);
tcphdr->th_dport = dest -->sin_port;
tcphdr->th_seq = 3;
tcphdr->th_ack = 0;
tcphdr->th_sum = 0;
tcphdr->th_off = 5;
tcphdr->th_flags = TH_SYN;
}
u16_t tcp_chksum (u16_t *addr, int len)
{
int nleft = len;
int sum = 0;
u16_t *temp = addr;
short ans = 0;
while (nleft > 1) {
sum += *temp++;
nleft -= 2;
}
if (nleft == 1) {
*(unsigned char ans) = *(unsigned short *)temp;
sum += ans;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
ans = ~sum;
return (ans);
}
void send_packet (int sockfd, unsigned short srcport, char *src, struct sockaddr_in *dest)
{
struct ip *iphdr;
struct tcphdr *tcphdr;
char buf[PACKET_LEN] = {0};
struct in_addr srcaddr;
int ip_len;
ip_len = sizeof(struct ip) + sizeof(struct tcphdr);
fprintf(stdout, "ip len: %d n", ip_len);
if (src) {
inet_aton(src, &srcaddr);
}
iphdr = (struct ip *)buf;
ip_packet_ctor(iphdr, dest);
tcphdr = (struct tcphdr *)(buf + sizeof(struct ip));
tcp_packet_ctor(tcphdr, srcpo rt, dest);
while (1) {
iphdr->ip_src.s_addr = (src == NULL) ? random() : srcaddr.s_addr;
tcphdr->th_sum = tcp_chksum((unsigned short *)tcphdr, sizeof(struct tcphdr));
sendto(sockfd, buf, ip_len, 0, (struct sockaddr *)dest, sizeof(struct sockaddr_in));
}
}
int main (int argc, char *argv[])
{
int sockfd;
struct sockaddr_in destaddr;
if (argc < 2) {
fprintf(stderr, "%s src addr dest addr. n", argv[0]);
return (-1);
}
sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
if (sockfd < 0) {
perror("socket");
return (-1);
}
bzero(&destaddr, sizeof(destaddr));
destaddr.sin_family = AF_INET;
destaddr.sin_len = sizeof(destaddr);
destad dr.sin_port = htons(DEST_PROT);
if (inet_aton(argv[2], &destaddr.sin_addr) == 0) {
fprintf(stderr, "destination addr don't found. n");
return (-1);
}
send_packet(sockfd, DEST_PROT, argv[1], &destaddr);
return (0);
}
翼辉系统原始套接字DEMO
于 2021-09-23 19:48:32 首次发布