#include #include #include #include #include using namespace std; const int BUFFER_SIZE{1000}; void PrintIP6Info(addrinfo * current); void PrintIP4Info(addrinfo * current); void PrintSocketType(addrinfo * current); int main() { string hostname{"mirkwood.cs.edinboro.edu"}; string service{"ssh"}; cout << "Enter the host name : "; cin >> hostname; cout << endl; cout << "Enter the service name : "; cin >> service; cout << endl; addrinfo *res; addrinfo hints; // Kerrisk or the man page reccomends this memset(&hints, 0, sizeof(hints)); // give it some clue what I am looking for. hints.ai_flags |= AI_CANONNAME; //hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_DGRAM; int errCode; errCode= getaddrinfo(hostname.c_str(), service.c_str(), &hints, &res); if (0 != errCode) { cout << "Get Address Error: " << gai_strerror(errCode) << endl; cout << "Name: " << hostname.c_str() << endl; cout << "Service: " << service.c_str() << endl; return 1; } else { addrinfo * current{res}; while (current != nullptr) { cout << endl; if (current->ai_canonname != nullptr) { cout << "Name : " << current->ai_canonname << endl; } cout << "\tFamily: " ; switch(current->ai_family) { case AF_INET6: PrintIP6Info(current); break; case AF_INET: PrintIP4Info(current); break; default: cout << "Unknown" << endl; } PrintSocketType(current); current = current->ai_next; } } freeaddrinfo(res); return 0; } void PrintSocketType(addrinfo * current) { cout << "\tSocket Type: "; switch (current->ai_socktype) { case SOCK_STREAM: cout << " stream " << endl; break; case SOCK_DGRAM: cout << " datagram " << endl; break; case SOCK_RAW: cout << "raw " << endl; break; case SOCK_RDM: cout << "reliable datagram" << endl; break; case SOCK_SEQPACKET: cout << "Sequenced reliable datagram" << endl; break; default: cout << "Unknown (" << current->ai_socktype << ")" << endl; } } void PrintIP4Info(addrinfo * current){ sockaddr_in * ptr; int port; in_addr *address; char buffer[BUFFER_SIZE]; cout << "\tIPv4" << endl; ptr = reinterpret_cast(current->ai_addr); // remember this is a 32 bit unsigned int. address = &(ptr->sin_addr); // net to host short. port = ntohs(ptr->sin_port); // inet_ntop converts to character string inet_ntop(current->ai_family, address, buffer, BUFFER_SIZE); cout << "\tIP : " << buffer << endl; cout << "\tPort: " << port << endl; } void PrintIP6Info(addrinfo * current){ sockaddr_in6 * ptr; int port; char buffer[BUFFER_SIZE]; in6_addr *address; ptr = reinterpret_cast(current->ai_addr); address = &(ptr->sin6_addr); port = ntohs(ptr->sin6_port); cout << "\tIPv6" << endl; inet_ntop(current->ai_family, address, buffer, BUFFER_SIZE); cout << "\tIP : " << buffer << endl; cout << "\tPort: " << port << endl; }