【问题标题】:SOCK_RAW packets don't send with certain source addressSOCK_RAW 数据包不使用特定源地址发送
【发布时间】:2012-05-12 20:51:18
【问题描述】:

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

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

当我运行ifconfig 时,只要我提供的源 IP 不是列为我的“真实”IP,代码就成功发送了一个在 Wireshark 中可见的数据包。谁能告诉我为什么会这样或者我可以如何解决它(除了不使用SOCK_RAW)?我会假设操作系统会特别处理数据包,但为什么呢?

【问题讨论】:

    标签: c sockets ip


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 1970-01-01
      • 2012-10-14
      • 2022-01-19
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      相关资源
      最近更新 更多