IPv6 && getaddrinfo(3C)

Doug Hardie bc979 at lafn.org
Thu Jul 12 21:21:41 UTC 2012


On 12 July 2012, at 07:24, Matthias Apitz wrote:

> 
> Hello,
> 
> I'm playing around with IPv6 code on a FreeBSD 9 system and can't get
> getaddrinfo(3C) to do what it should do as stated in its man page:
> accept an IPv6 and IPv4 IP addr, it only works with the IPv6 form:
> 
> $ ./a.out ::1
> host: ::1
> read: SSH-2.0-OpenSSH_5.6p1 FreeBSD-20101111
> $ ./a.out 127.0.0.1
> host: 127.0.0.1
> ssh: getaddrinfo failed code 8: hostname nor servname provided, or not known
> $ telnet 127.0.0.1 22
> Trying 127.0.0.1...
> Connected to localhost.
> Escape character is '^]'.
> SSH-2.0-OpenSSH_5.6p1 FreeBSD-20101111
> 
> the used C-code is attached below; what I'm doing wrong in the code?
> 
> Thanks
> 
> 	matthias
> 
> /* IPv6 client code using getaddrinfo */
> 
> #include <stdlib.h>
> #include <sys/types.h>
> #include <sys/socket.h>
> #include <netinet/in.h>
> #include <stdio.h>
> #include <netdb.h>
> #include <string.h>
> 
> 
> main(argc, argv)		/* client side */
> 	int		argc;
> 	char           *argv[];
> {
> 
> 	struct addrinfo	req, *ans;
> 	int	code, s, n;
> 	char buf[1024];
> 
> 	memset(&req, 0, sizeof(req));
> 	req.ai_flags = AI_ADDRCONFIG|AI_NUMERICHOST;
> 	req.ai_family = AF_INET6;	/* Same as AF_INET6. */
> 	req.ai_socktype = SOCK_STREAM;
> 
> 	/*                                         */
> 	/* Use default protocol (in this case tcp) */
> 	/*                                         */
> 
> 	req.ai_protocol = 0;
> 
> 	printf("host: %s\n", argv[1]);
> 	if ((code = getaddrinfo(argv[1], "ssh", &req, &ans)) != 0) {
> 		fprintf(stderr, "ssh: getaddrinfo failed code %d: %s\n", code, gai_strerror(code));
> 		exit(1);
> 	}
> 	 
> 	 
> 	/*                                             */
> 	/* ans must contain at least one addrinfo, use */
> 	/* the first.                                  */
> 	/*                                             */ 
> 	
> 	s = socket(ans->ai_family, ans->ai_socktype, ans->ai_protocol);
> 	if (s < 0) {
> 		perror("ssh: socket");
> 		exit(3);
> 	}
> 
> 	/* Connect does the bind for us */
> 	
> 	if (connect(s, ans->ai_addr, ans->ai_addrlen) < 0) {
> 		perror("ssh: connect");
> 		exit(5);
> 	}
> 
> 	n = read(s, buf, 1024);
> 	printf ("read: %s", buf);
> 	
> 	/* */
> 	/* Free answers after use */
> 	/* */ 
> 	freeaddrinfo(ans);
> 
> 	exit(0);
> }
> 
>  

I won't claim to be an expert on this, but I have used getaddrinfo successfully in servers.  The only thing I see that might be an issue is the use of zero for ai_protocol.  The comment in the man page implies that value is for servers and not clients.  I suspect you have to set the specific protocol you want.  You haven't included AI_PASSIVE so I suspect its expecting you to use the address to contact a server.




More information about the freebsd-questions mailing list