Error: Bad address when using sendto() in raw sockets

Error: Bad address when using sendto() in raw sockets

我正在编写一个简单的网络应用程序,我需要制作一个 UDP 数据包并将其发送到特定主机。

int main(void){

    // Message to be sent.
    char message[] = "This is something";

    int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);

    if(sockfd < 0){
        perror("Error creating socket");
        exit(1);
    }

    struct sockaddr_in this, other;

    this.sin_family = AF_INET;
    other.sin_family = AF_INET;


    this.sin_port = htons(8080);
    other.sin_port = htons(8000);


    this.sin_addr.s_addr = INADDR_ANY;
    other.sin_addr.s_addr = inet_addr("10.11.4.99");

    if(bind(sockfd, (struct sockaddr *)&this, sizeof(this)) < 0){
        printf("Bind failed\n");
        exit(1);
    }

    char packet[64] = {0};

    struct udphdr *udph = (struct udphdr *) packet;
    strcpy(packet + sizeof(struct udphdr), message);

    udph->uh_sport = htons(8080);
    udph->uh_dport = htons(8000);
    udph->uh_ulen = htons(sizeof(struct udphdr) + sizeof(message));
    udph->uh_sum = 0;

    if(sendto(sockfd, packet, udph->uh_ulen, 0, (struct sockaddr *) &other, sizeof(other)) < 0)
        perror("Error");
    else
        printf("Packet sent successfully\n");

    close(sockfd);

    return 0;
}

在调用 sendto() 之前一切正常。 sendto() 正在给出 "Bad address"。谁能指出我哪里出错了?将端口绑定到原始套接字是否有任何问题?

代码将消息的长度 (udph->uh_len) 转换为网络字节顺序 (htons)。这个不需要,因为size_t的参数类型。只有端口号(在 sockaddr 结构中)需要 htons 转换。

    udph->uh_ulen = sizeof(struct udphdr) + sizeof(message);

当前代码在 uh_ulen 中产生大量 (>8000),导致发送失败。