为什么对sendto()的调用失败?

时间:2012-01-27 19:35:03

标签: c linux network-programming udp

我正在尝试发送一个具有特定有效负载的UDP数据包,而我对sendto()的调用在运行时失败。这是我的第一个socket编程实验。

原始代码是较大项目的一部分,但我已将其简化为更简单的测试程序:

#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");
 }

这是输出:sendto: Invalid argument

根据要求输出一些gdb:

(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

1 个答案:

答案 0 :(得分:2)

您未能为service指定getaddrinfo参数。请尝试调用getaddrinfo

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

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