【问题标题】:Error: Bad address when using sendto() in raw sockets错误:在原始套接字中使用 sendto() 时地址错误
【发布时间】:2020-02-20 08:32:33
【问题描述】:

我正在编写一个简单的网络应用程序,我需要制作一个 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() 给出“错误地址”。谁能指出我哪里出错了?将端口绑定到原始套接字有什么问题吗?

【问题讨论】:

    标签: c sockets network-programming udp raw-sockets


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,我错过了。你付出了这么多的努力。
    猜你喜欢
    • 2017-02-02
    • 2015-05-26
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2022-01-19
    • 2012-06-15
    相关资源
    最近更新 更多