我正在尝试将UDP数据包发送到argv [1]中包含的地址,该地址可以是IPv4,IPv6或主机名。当地址为IPv4时,UDP数据包成功发送,但是当我使用主机名或IPv6地址时,sendto()会抛出错误101“sendto:网络无法访问”。为什么只有在我不使用IPv4时才能访问网络?我正在运行ubuntu 14.04,如果这有帮助的话。
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[]) {
int sockfd, ret;
struct addrinfo ai_hints;
struct addrinfo *ai_results;
/* create an IPv6 UDP socket */
sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
if (sockfd == -1) {
perror("socket");
return 1;
}
/* find UDP IPv6 addresses from command line arg */
memset(&ai_hints, 0, sizeof(ai_hints));
ai_hints.ai_family = AF_INET6;
ai_hints.ai_socktype = SOCK_DGRAM;
ai_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG; /* defaults */
ret = getaddrinfo(argv[1], "12345", &ai_hints, &ai_results);
if (ret != 0) {
fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(ret));
return 1;
}
ret = sendto(
sockfd, "Hello World", 11, 0,
ai_results->ai_addr, ai_results->ai_addrlen
);
if (ret == -1) {
printf("errno: %i\n",errno);
perror("sendto");
return 1;
}
}