首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SOCK_RAW数据包不使用某些源地址发送

SOCK_RAW数据包不使用某些源地址发送
EN

Stack Overflow用户
提问于 2012-05-13 04:51:18
回答 1查看 966关注 0票数 1

我正在开发一个类似netcat的工具(主要用于自我教育)。我想通过SOCK_RAW套接字发送带有IP和UDP头的数据包。我在Debian VM上运行以下代码,通过套接字发送数据包。

代码语言:javascript
复制
/* header must already have source IP, destination IP, and protocol number filled in */
int send_ip_packet(ipheader_t *header, char *buf, int numbytes)
{
    int sizeofpacket = sizeof(ipheader_t) + numbytes;
    if(sizeofpacket > MAX_PCKT_LEN)
    {
        printf("Cannot send ip packet of len %i. Too large. - FAIL\n", sizeofpacket);
        return -1;
    }

    /* open a raw socket */
    int sd;
    sd = socket(PF_INET, SOCK_RAW, header->ip_p);
    if(sd < 0)
    {
        perror("socket()");
        printf("socket() call - FAIL\n");
        return -1;
    }
    else
    {
        printf("socket() call - SUCCESS\n");
    }

    char packet[sizeofpacket];
    memset(packet, 0, sizeofpacket);

    /* set remaining ip header */
    header->ip_hl = 5; /* header length is 5 32-bit octets */
    header->ip_v = 4; /* IPv4 */
    header->ip_tos = 16; /* low delay */
    header->ip_len = sizeofpacket;
    header->ip_id = htons(54321); /* identifier used for fragmentation */
    header->ip_off = 0; /* fragmentation options */
    header->ip_ttl = 64; /* max num hops */
    header->ip_sum = csum((unsigned short*)packet, sizeofpacket);

    /* fill packet */
    memcpy(packet, (char*) header, sizeof(ipheader_t));
    memcpy(packet + sizeof(ipheader_t), (char*) buf, numbytes);

    /* setup socket addresses */
    struct sockaddr_in sin, din;
    sin.sin_family = AF_INET;
    din.sin_family = AF_INET;
    memcpy(&sin.sin_addr.s_addr, &header->ip_src, sizeof(in_addr_t));
    memcpy(&din.sin_addr.s_addr, &header->ip_dst, sizeof(in_addr_t));

    /* send out the packet */
    int one = 1;
    int *val = &one;
    if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)))
    {
        perror("setsockopt()");
        printf("setsockopt() call - FAIL\n");
        return -1;
    }
    else
    {
        printf("setsockopt() call - SUCCESS\n");
    }

    if(sendto(sd, packet, header->ip_len, 0, (struct sockaddr *) &sin, sizeof(sin)) < 0)
    {
        perror("sendto()");
        printf("sendto() call - FAIL\n");
        return -1;
    }
    else
    {
        printf("Message sent! - SUCCESS\n");
    }

    return 0;
}

只要我提供的源IP不是我运行ifconfig时列出的“真实”IP,代码就会成功地发送一个在wireshark中可见的数据包。有没有人能告诉我为什么会出现这种情况,或者我可以如何修复它(除了不使用SOCK_RAW)?我会假设操作系统正在特殊处理数据包,但为什么呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-13 16:01:47

sendto()期望目标地址作为第5个参数。

根据OP中给出的变量命名,我强烈假设传入了源地址,这将完美地解释所描述的行为。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10567328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档