#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <unistd.h>

/* Checksum calculation function */
unsigned short in_cksum (unsigned short *buf, int length) {
    unsigned short *w = buf;
    int nleft = length;
    int sum = 0;
    unsigned short temp=0;

    while (nleft > 1)  {
        sum += *w++;
        nleft -= 2;
    }

    if (nleft == 1) {
        *(u_char *)(&temp) = *(u_char *)w ;
        sum += temp;
    }

    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

void send_raw_ip_packet(struct iphdr* ip) {
    struct sockaddr_in dest_info;
    int enable = 1;

    int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    if (sock < 0) {
        perror("Socket creation failed");
        return;
    }

    setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &enable, sizeof(enable));

    dest_info.sin_family = AF_INET;
    dest_info.sin_addr.s_addr = ip->daddr;

    if (sendto(sock, ip, ntohs(ip->tot_len), 0, (struct sockaddr *)&dest_info, sizeof(dest_info)) < 0) {
        perror("Sendto failed");
    } else {
        printf("Spoofed ICMP packet sent.\n");
    }
    close(sock);
}

int main() {
    char buffer[1500];
    memset(buffer, 0, 1500);

    struct iphdr *ip = (struct iphdr *) buffer;
    struct icmphdr *icmp = (struct icmphdr *) (buffer + sizeof(struct iphdr));

    // Construct ICMP Header
    icmp->type = ICMP_ECHO;
    icmp->code = 0;
    icmp->un.echo.id = htons(1234);
    icmp->un.echo.sequence = htons(1);
    icmp->checksum = 0;
    icmp->checksum = in_cksum((unsigned short *)icmp, sizeof(struct icmphdr));

    // Construct IP Header
    ip->version = 4;
    ip->ihl = 5;
    ip->ttl = 64;
    ip->saddr = inet_addr("1.2.3.4");
    ip->daddr = inet_addr("10.9.0.5");
    ip->protocol = IPPROTO_ICMP;
    ip->tot_len = htons(sizeof(struct iphdr) + sizeof(struct icmphdr));

    send_raw_ip_packet(ip);

    return 0;
}
