C 错误:在原始套接字中使用sendto()时地址错误

C 错误:在原始套接字中使用sendto()时地址错误,c,sockets,network-programming,udp,raw-sockets,C,Sockets,Network Programming,Udp,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");

我正在编写一个简单的网络应用程序,我需要创建一个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;
}
int main(无效){
//要发送的消息。
char message[]=“这是一件大事”;
int-sockfd=套接字(AF_INET、SOCK_RAW、IPPROTO_UDP);
if(sockfd<0){
perror(“创建套接字时出错”);
出口(1);
}
此中的结构sockaddr_,其他;
this.sin_family=AF_INET;
other.sin_family=AF_INET;
此.sinu端口=htons(8080);
other.sin_port=htons(8000);
this.sin_addr.s_addr=INADDR\u ANY;
other.sin_addr.s_addr=inet_addr(“10.11.4.99”);
if(bind(sockfd,(struct sockaddr*)&this,sizeof(this))<0){
printf(“绑定失败\n”);
出口(1);
}
字符包[64]={0};
结构udphdr*udph=(结构udphdr*)数据包;
strcpy(数据包+sizeof(结构udphdr),消息);
udph->uh_sport=htons(8080);
udph->uh_dport=htons(8000);
udph->uh_ulen=htons(sizeof(struct udphdr)+sizeof(message));
udph->uh_sum=0;
if(发送到(sockfd,packet,udph->uh_-ulen,0,(struct sockaddr*)和其他,sizeof(其他))<0)
佩罗(“错误”);
其他的
printf(“数据包成功发送\n”);
关闭(sockfd);
返回0;
}

在调用sendto()之前,一切正常。sendto()给出了“错误地址”。有人能告诉我哪里出了问题吗?将端口绑定到原始套接字是否有问题?

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

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

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

是的,我错过了。谢谢你的努力。