getaddrinfo e inet_ntop exemplos

Postagem de conteúdo sobre programação C, C++ e C#
Post Reply
Zaphod
Admin
Admin
Posts: 19
Joined: Fri Jan 02, 2015 1:24 pm

getaddrinfo e inet_ntop exemplos

Post by Zaphod » Thu Feb 26, 2015 1:24 pm

as funções gethostbyname, inet_ntoa e inet_aton, são obsoletas, não tem suporte para ipv6, mas mesmo assim é comum serem usadas, aqui vai um exemplo usando a função getaddrinfo que substitui gethostname, e inet_ntop que substitui inet_ntoa:

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
 
int main(int argc, char **argv){
	int rv;
	struct addrinfo hints, *servinfo, *p;
	char ipv6[INET6_ADDRSTRLEN], ipv4[INET_ADDRSTRLEN];
 
	if(argc != 2){
		printf("%s <host>\n",argv[0]);
		return 1;
 	}
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags |= AI_CANONNAME;
 
	if ((rv = getaddrinfo(argv[1], NULL, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		exit(1);
	}
 
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if(AF_INET6 == p->ai_family){
			inet_ntop(AF_INET6, &((struct sockaddr_in6 *)(p->ai_addr))->sin6_addr, ipv6, INET6_ADDRSTRLEN);
			printf("Ipv6: %s\n", ipv6);
		}
		else if(AF_INET == p->ai_family) {
			inet_ntop(AF_INET, &((struct sockaddr_in *)(p->ai_addr))->sin_addr, ipv4, INET_ADDRSTRLEN);
			printf("Ipv4: %s\n", ipv4);
		}
 
		else
			printf("Unknow\n");
 
		/*int sockfd;

		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
			perror("socket");
			continue;
		}

		((struct sockaddr_in *)p->ai_addr)->sin_port = htons(443);

		if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("connect");
			continue;
		}*/
 
	}
 
	freeaddrinfo(servinfo);
 
	return 0;
 
}
+[----->+++<]>+.+.

Post Reply

Return to “C / C++ / C#”