1I'm reading Beej's programming network guide. I read his code and did an important change to check ipv6 but it's not working right. Can't get an ip Address. How to use this on a Linux system? https://i.imgur.com/USVzBw1.png
#include <stdio.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct addrinfo hints, *res, *p;
int status;
char ipstr[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf(stderr,"usage: showip hostname\n");
return 1;
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
hints.ai_socktype = SOCK_STREAM;
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
return 2;
}
printf("IP addresses for %s:\n\n", argv[1]);
for(p = res;p != NULL; p = p->ai_next) {
void *addr;
char *ipver;
// get the pointer to the address itself,
// different fields in IPv4 and IPv6:
if (p->ai_family == AF_INET) { // IPv4
struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
addr = &(ipv4->sin_addr);
ipver = "IPv4";
} else if (p->ai_family==AF_INET6) { // IPv6
struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
addr = &(ipv6->sin6_addr);
ipver = "IPv6";
}
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
}
freeaddrinfo(res); // free the linked list
return 0;
}```
This looks suspicious:
You check to make sure argc
is 2 to validate you have at least one argument. Makes sense
if (argc != 2) {
But then later:
if ((status = getaddrinfo(argv[2], NULL, &hints, &res)) != 0) {
You reference argv[2]
, which is undefined when the only valid indicies in argv
are 0
and 1
.
Pretty sure you meant to use argv[1]
as follows:
if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
Also, this is a bug:
// convert the IP to a string and print it:
inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
printf(" %s: %s\n", ipver, ipstr);
Nothing wrong with those statements, but when p->ai_family
is neither AF_INET
nor AF_INET6
, then those statements get executed anyway. addr
and ipver
are undefined. Hence, undefined behavior. And yes, on Linux, there's plenty of address types that are not IP based.
You are welcome to reference my ResolveHostname function on Github .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.