任何想法为什么这个DNS查找程序抛出“分段错误:11”?
我发现它与分配的内存有关,但不知道它在哪里发生。
谢谢。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
int main()
{
int sockfd;
struct addrinfo hints, *results, *p;
struct sockaddr_in *ip_access;
int rv;
char *hostname;
char ip[100], inputVal[100];
printf("Enter a domain name: \n");
scanf("%s", inputVal);
strcpy(hostname, inputVal);
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if((rv = getaddrinfo(hostname, "domain", &hints, &results)) != 0)
{
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through structure using ai_next
for(p= results; p != NULL; p = p->ai_next)
{
// pass data into sockaddr in struct
ip_access = (struct sockaddr_in *) p->ai_addr;
printf("IP address is %s: \n", inet_ntoa(ip_access->sin_addr));
}
freeaddrinfo(results);
printf("\n");
}
hostname
未初始化,你没有为它分配任何空间,所以strcpy(hostname, inputVal);
调用未定义的行为。您可以通过动态分配空间来解决此问题:
char *hostname = malloc(100);
if (hostname == NULL)
{
// you can handle this error anyway you like, this is just an example
fprintf(stderr, "Out of memory\n");
exit(-1);
}
...
// after you're done using hostname, cleanup
free(hostname);
或者您可以像使用ip
和inputVal
一样在自动存储中为其分配空间:
char hostname[100];
我更喜欢这个例子中的自动存储解决方案。事实上,我可能完全摆脱inputVal
而且只是这样做
char hostname[100];
scanf("%99s", hostname); // %99s ensures only 99 characters of data will be read from stdin,
// leaving room for the NUL terminator. Hostnames can get
// long, so you may want more than 100 characters.
从那里开始
您根本不需要inputVal
数组,因为您只扫描一个字符串。使用char hostname[100]
代替,segfault应该消失。