简体   繁体   中英

UDP Raw Socket set message

So, I have the raw sockets set up with some copypasta, it sends data, that part is working fine. But how would I set the data send over the socket? I'm looking to make a DNS request, if that helps. Code below.

int main(int argc, char *argv[])
{
    if (!argv[1])
    {
        printf("Target not specified!\nUsage: ");
        printf(argv[0]);
        printf(" <target>\n");
        exit(1);
    }

    struct ip ip;
    struct udphdr udp;
    int sd;
    const int on = 1;
    struct sockaddr_in sin;
    //char msg[] = "\x03\xF0\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01";
    u_char *packet;
    packet = (u_char *)malloc(120);


    ip.ip_hl = 0x5;
    ip.ip_v = 0x4;
    ip.ip_tos = 0x0;
    ip.ip_len = 60;
    ip.ip_id = htons(12830);
    ip.ip_off = 0x0;
    ip.ip_ttl = 64;
    ip.ip_p = IPPROTO_UDP;
    ip.ip_sum = 0x0;
    ip.ip_src.s_addr = inet_addr(argv[1]);
    ip.ip_dst.s_addr = inet_addr("67.228.44.4");
    ip.ip_sum = in_cksum((unsigned short *)&ip, sizeof(ip));
    memcpy(packet, &ip, sizeof(ip));

    udp.source = htons(80);
    udp.dest = htons(53);
    udp.len = htons(22);
    udp.check = 0;
    udp.check = in_cksum_udp(ip.ip_src.s_addr, ip.ip_dst.s_addr, (unsigned short *)&udp, sizeof(udp));
    memcpy(packet + 20, &udp, sizeof(udp));

    if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) {
        perror("raw socket");
        exit(1);
    }

    if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) {
        perror("setsockopt");
        exit(1);
    }
    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = ip.ip_dst.s_addr;

    if (sendto(sd, packet, 120, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0)  
    {
        perror("sendto");
        exit(1);
    }
}

Hmmm...I think you're wondering how to set the payload in your message? Basically, you want to offset from the IP and UDP headers and start writing your payload data at that point.

A hastily thrown together example of this:

int offset = packet + sizeof(struct ip) + sizeof(struct udphdr);

Then you can write your payload as follows:

strcpy(offset, "1234");

Here's some working ICMP code that is effectively writing out the data over a RAW IP socket:

struct icmphdr *icmp_hdr; 
char *datapart; 

icmp_hdr = (struct icmphdr *) icmp_data; 
icmp_hdr->i_type = ICMP_ECHO; 
icmp_hdr->i_code = 0; 
icmp_hdr->i_id = (unsigned short) getpid();
icmp_hdr->i_cksum = 0; 
icmp_hdr->i_seq = 0; 
datapart = icmp_data + sizeof(struct icmphdr); 
memset(datapart, 'E', datasize - sizeof(struct icmphdr));  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM