Reputation: 3865
My target machine for some socket communication application in a LAN has 192.168.98.91
for IPv4.
When I try to resolve IPaddress with getaddrinfo() it returns 127.0.0.1
How can I get 192.168.98.91
?
I've set 192.168.98.91
for myhost
in /etc/hosts
file and ping I did to myhost
showed 192.168.98.91
as IP address.
My machine is CentOS6.4.
This is setting of /etc/hosts.
192.168.98.91 myhost
127.0.0.1 myhost localhost.localdomain
This is my code.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <arpa/inet.h>
int
main(int argc,char *argv[]){
int sock;
struct addrinfo hints,*res;
int n;
int err;
if(argc != 2){
fprintf(stderr,"Usage : %s dst \n",argv[0]);
return 1;
}
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
err = getaddrinfo(argv[1],"12345",&hints,&res);
if(err != 0){
perror("getaddrinfo");
printf("getaddrinfo %s\n",strerror(errno));
printf("getaddrinfo : %s \n",gai_strerror(err));
return 1;
}
sock = socket(res->ai_family,res->ai_socktype,0);
if(sock < 0){
perror("socket");
return 1;
}
{
const char *ipverstr;
switch (res->ai_family){
case AF_INET:
ipverstr = "IPv4";
break;
case AF_INET6:
ipverstr = "IPv6";
break;
default:
ipverstr = "unknown";
break;
}
printf("ipverstr = %s\n ",ipverstr);
}
n = sendto(sock,"HELLO",5,0,res->ai_addr,res->ai_addrlen);
//n = sendto(sock,"HELLO", 5, 0,(struct sockaddr *)addr, sizeof(addr));
if(n<1){
perror("sendto");
{
}
return 1;
}
struct sockaddr_in *addr;
addr = (struct sockaddr_in *)res->ai_addr;
printf("inet_ntoa(in_addr)sin = %s\n",inet_ntoa((struct in_addr)addr->sin_addr));
printf("############ finish !! #######\n");
close(sock);
freeaddrinfo(res);
return 0;
}
Upvotes: 0
Views: 2865
Reputation: 70883
If you'd follow the chain of results returned by getaddrinfo()
using the ai_next
member of struct addrinfo
you'd also get 192.168.98.91
for myhost
.
Here http://man7.org/linux/man-pages/man3/getaddrinfo.3.html you find a full example also showing how to do this:
From the link above:
...
s = getaddrinfo(NULL, argv[1], &hints, &result);
if (s != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
/* Do something with rp->ai_family, rp->ai_socktype, ... */
}
...
Removing myhost
from this line in /etc/hosts
:
127.0.0.1 myhost localhost.localdomain
would result in 127.0.0.1
not being returned by getaddrinfo()
anymore when asking it for myhost
.
Upvotes: 5