*
****************************************************************/
#include <arpa/inet.h>
+#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
+#include <unistd.h>
int sockconn(char *host, char *serv, int prot, int type)
{
struct addrinfo hint, *addr, *save;
int res;
int sock;
+ int err;
+ char buffer[INET6_ADDRSTRLEN];
+ struct sockaddr_in *ip4;
+ struct sockaddr_in6 *ip6;
/* initialize hint structure */
memset(&hint, 0, sizeof(struct addrinfo));
hint.ai_family = PF_UNSPEC; /* generic address (IPv4 or IPv6) */
/* loop on possible addresses */
save = addr;
while (addr != NULL) {
+ if (addr->ai_family == PF_INET) {
+ ip4 = (struct sockaddr_in *) addr->ai_addr;
+ printf("Indirizzo %s\n", inet_ntop(ip4->sin_family, &ip4->sin_addr,
+ buffer, sizeof(buffer)));
+ } else {
+ ip6 = (struct sockaddr_in6 *) addr->ai_addr;
+ printf("Indirizzo %s\n", inet_ntop(ip6->sin6_family,
+ &ip6->sin6_addr,
+ buffer, sizeof(buffer)));
+ }
/* get a socket */
sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (sock < 0) {
- if (addr->ai_next == NULL) {
+ if (addr->ai_next != NULL) {
addr=addr->ai_next;
continue;
} else {
/* connect the socket */
res = connect(sock, addr->ai_addr, addr->ai_addrlen);
if (res < 0) {
- if (addr->ai_next == NULL) {
+ if (addr->ai_next != NULL) {
close(sock);
addr=addr->ai_next;
continue;
} else {
+ err = errno;
+ close(sock);
+ errno = err;
printf("sockconn cannot connect socket\n");
return res;
}
- }
+ } else break;
}
freeaddrinfo(save); /* done, release memory */
return sock;