生成ip + udp头时出现分段错误

时间:2014-12-01 00:52:58

标签: c windows sockets cygwin

我正在尝试制作一个看似简单的概念:一个程序,它发送自定义UDP数据包供我在本地机器上嗅探;但是我无法理解为什么我会遇到这种分段错误:

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: 我想我应该发布我的结构:

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;
};

1 个答案:

答案 0 :(得分:0)

我的端口现在是整数,而不是字符串:

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

应改为:

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