我正在写一个告诉域名ip地址的代码。以下代码工作正常。
MERGE
当我尝试使用void *来存储struct sockaddr_in sin_addr或struct sockaddr_in6 sin6_addr时,我收到了以下错误。 “getaddrinfo错误:不支持ai_socktype”
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <string.h>
#include <arpa/inet.h>
#define SUCCESS 0
#define FAILURE -1
int main(int argc, char *argv[])
{
if(argc != 2) {
printf("./a.out <domain>\n");
return FAILURE;
}
struct addrinfo src,*res,*var;
struct sockaddr_in *ipv4;
struct sockaddr_in6 *ipv6;
char ipstr[INET6_ADDRSTRLEN];
int status;
src.ai_family=AF_UNSPEC;
src.ai_socktype=SOCK_STREAM;
src.ai_flags=AI_PASSIVE;
if((status = getaddrinfo(argv[1],NULL,&src,&res))!=0) {
fprintf(stderr,"getaddrinfo error:%s\n",gai_strerror(status));
exit(1);
}
for(var = res;var != NULL;var = var->ai_next) {
if(var->ai_family == AF_INET) {
ipv4 = (struct sockaddr_in *) var->ai_addr;
inet_ntop(var->ai_family,&(ipv4->sin_addr),ipstr,INET6_ADDRSTRLEN);
}
else {
ipv6 = (struct sockaddr_in6 *) var->ai_addr;
inet_ntop(var->ai_family,&(ipv6->sin6_addr),ipstr,INET6_ADDRSTRLEN);
}
printf("IP address:%s\n",ipstr);
}
freeaddrinfo(res);
freeaddrinfo(var);
return SUCCESS;
}
我是套接字编程的初学者。请帮我解决这个问题。