rps
rps

Reputation: 1293

Why is this call to sendto() failing?

I'm trying to send a single UDP packet with a specific payload and my call to sendto() is failing at runtime. This is my first experiment with socket programming.

The original code is part of a larger project, but I've reduced it to a much simpler test program:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>

#define SIZE 16

int main()
{
     int sock;
     struct sockaddr *addr;
     socklen_t addrlen;
     struct addrinfo hints, *result;
     char *url = "tracker.openbittorrent.com";
     void *payload = malloc(SIZE);

     memset(&hints, 0, sizeof(struct addrinfo));
     hints.ai_family = AF_INET;
     hints.ai_socktype = SOCK_DGRAM;
     hints.ai_flags = 0;
     hints.ai_protocol = IPPROTO_UDP;
     hints.ai_canonname = NULL;
     hints.ai_addr = NULL;
     hints.ai_next = NULL;

     int er = getaddrinfo(url, NULL, &hints, &result);
     if (er != 0) {
          fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(er));
          exit(EXIT_FAILURE);
     }

     sock = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
     if (sock == -1) {
          perror("socket");
          exit(EXIT_FAILURE);
     }

     if (sendto(sock, payload, SIZE, 0, result->ai_addr, result->ai_addrlen) == -1)
          perror("sendto");
 }

Here's the output: sendto: Invalid argument

Some gdb output, as requested:

(gdb) p result->ai_addr->sa_data 
 $3 = "\000\000_\327>\005\000\000\000\000\000\000\000"
(gdb) p result->ai_addr->sa_family
 $4 = 2
(gdb) p result->ai_addrlen
 $5 = 16
(gdb) p result->ai_canonname
 $6 = 0x0
(gdb) p result->ai_flags
 $8 = 0
(gdb) p result->ai_protocol
 $9 = 17
(gdb) p result->ai_socktype
 $10 = 2

Upvotes: 0

Views: 1694

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

You failed to specify a service parameter to getaddrinfo. Try invoking getaddrinfo thus:

int er = getaddrinfo(url, "9", &hints, &result);

or

int er = getaddrinfo(url, "discard", &hints, &result);

Upvotes: 2

Related Questions