Karthik Chennupati
Karthik Chennupati

Reputation: 365

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

I'm writing a simple network application and I need to craft a UDP packet and send it to a specific host.

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

Everything is working fine till the call to sendto(). The sendto() is giving "Bad address". can anyone point me where I'm going wrong? Is there any problem with binding a port to a raw socket?

Upvotes: 1

Views: 634

Answers (1)

dash-o
dash-o

Reputation: 14452

The code transform the length of the messag (udph->uh_len) to network byte order (htons). This is not needed, as the parameter type of size_t. Only port number (in sockaddr structures) need the htons conversion.

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

Current code produce large number (>8000) in uh_ulen, causing the send to fail.

Upvotes: 2

Related Questions