Search code examples
cwindowssocketscygwin

Segmentation fault while generating ip + udp header


I am trying to make what seems to be a simple concept: a program that sends custom UDP packets for me to sniff out on a local machine; but I am failing to understand why I am getting this segmentation fault:

int main() {
    int sd;
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    short int buf[PCKT_LEN];
    memset(buf, 0, PCKT_LEN);
    struct ipheader *ip = buf;
    struct udpheader *udp = buf + sizeof(struct ipheader);
    short int *data = buf + sizeof(struct ipheader) + sizeof(struct udpheader);
    int datalen = PCKT_LEN - sizeof(struct ipheader) + sizeof(struct udpheader) - 1;
    ip->iph_ihl = 5;
    ip->iph_ver = 4;
    ip->iph_tos = 16;
    ip->iph_len = PCKT_LEN;
    ip->iph_ident = htons(1);
    ip->iph_protocol = PROTO;
    ip->iph_sourceip = inet_addr("0.0.0.0");
    ip->iph_destip = inet_addr("0.0.0.0");
    udp->udph_srcport = htons(atoi(PORT));
    udp->udph_destport = htons(atoi(PORT));
    udp->udph_len = htons(sizeof(struct udpheader));
    ip->iph_chksum = csum(buf, PCKT_LEN);
    while (~0) {
        short int *ptr = data, *end = data + datalen, c;
        while (ptr < end && (c = getc(stdin)) != '\n' && c != '\r')
            *ptr++ = c;
        send(sd, buf, PCKT_LEN, 0);
        sleep (1000); 
    }
}

$ ./server
Segmentation fault (core dumped)

Ammendment: I guess I should post my structures:

struct ipheader {
    unsigned char      iph_ihl:5, iph_ver:4;
    unsigned char      iph_tos;
    unsigned short int iph_len;
    unsigned short int iph_ident;
    unsigned char      iph_flag;
    unsigned short int iph_offset;
    unsigned char      iph_ttl;
    unsigned char      iph_protocol;
    unsigned short int iph_chksum;
    unsigned int       iph_sourceip;
    unsigned int       iph_destip;
};

struct udpheader {
 unsigned short int udph_srcport;
 unsigned short int udph_destport;
 unsigned short int udph_len;
 unsigned short int udph_chksum;
};

Solution

  • My ports are integers now , not strings:

    udp->udph_srcport = htons(atoi(PORT));
    udp->udph_destport = htons(atoi(PORT));
    

    should change to:

    udp->udph_srcport = htons(PORT));
    udp->udph_destport = htons(PORT);