Created
September 27, 2013 11:49
-
-
Save RklAlx/6727410 to your computer and use it in GitHub Desktop.
Hostname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*NOTA: | |
1) tem que se garantir que o windows.h é compilado sempre após o ws2tcpip.h, | |
caso contrário começa a indicar que há referencias duplicadas. | |
2) Quando se trabalha com sockets tem sempre que se inicializar a WinSockDLL -> tag WSAStartup */ | |
#include <Ws2tcpip.h> | |
void ShowInfo(struct addrinfo *res) | |
{ | |
struct sockaddr_in *sockaddr_ipv4; | |
LPSOCKADDR sockaddr_ip; | |
char ipstringbuffer[46]; | |
DWORD ipbufferlength = 46; | |
INT iRetval; | |
switch(res->ai_family) | |
{ | |
case AF_UNSPEC: | |
printf("Unspecified\n"); | |
break; | |
case AF_INET: | |
printf("AF_INET (IPv4)\n"); | |
sockaddr_ipv4 = (struct sockaddr_in *) res->ai_addr; | |
printf("\tIPv4 address %s\n",inet_ntoa(sockaddr_ipv4->sin_addr) ); | |
break; | |
case AF_INET6: | |
printf("AF_INET6 (IPv6)\n"); | |
// the InetNtop function is available on Windows Vista and later | |
// sockaddr_ipv6 = (struct sockaddr_in6 *) ptr->ai_addr; | |
// printf("\tIPv6 address %s\n", | |
// InetNtop(AF_INET6, &sockaddr_ipv6->sin6_addr, ipstringbuffer, 46) ); | |
// We use WSAAddressToString since it is supported on Windows XP and later | |
sockaddr_ip = (LPSOCKADDR) res->ai_addr; | |
// The buffer length is changed by each call to WSAAddresstoString | |
// So we need to set it for each iteration through the loop for safety | |
ipbufferlength = 46; | |
iRetval = WSAAddressToString(sockaddr_ip, (DWORD) res->ai_addrlen, NULL, | |
ipstringbuffer, &ipbufferlength ); | |
if (iRetval) | |
printf("WSAAddressToString failed with %u\n", WSAGetLastError() ); | |
else | |
printf("\tIPv6 address %s\n", ipstringbuffer); | |
break; | |
default: | |
break; | |
} | |
} | |
// | |
// | |
// | |
bool ConvertCharIPToAddrInfo(char* addrOne,struct addrinfo*& pResult) //ex: pc-rteste or 127.0.0.1 or localhost (whatever u like :) | |
{ | |
int error = getaddrinfo(addrOne,NULL,NULL,&pResult); | |
if(error == 0) | |
return true; | |
} | |
bool ShowHostnameFromAddrInfo(struct addrinfo *result) | |
{ | |
char hostname_res[NI_MAXHOST] = ""; | |
int error; | |
struct addrinfo *res; | |
for (res = result; res != NULL; res = res->ai_next) | |
{ | |
error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname_res, NI_MAXHOST, NULL, 0, 0); | |
if (error != 0) | |
{ | |
fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error)); | |
return false; | |
} | |
if (*hostname_res == '\0') | |
{ | |
printf("no hostname found\n"); | |
return false; | |
} | |
printf("hostname: %s\n", hostname_res); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment