Advertisement
peterzig

[PWŚS] Hostname to IP

Feb 28th, 2017
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #define _WINSOCK_DEPRECATED_NO_WARNINGS
  2.  
  3. #include <WinSock2.h>
  4. #include <stdio.h>
  5.  
  6. #pragma comment(lib,"ws2_32.lib")
  7.  
  8. int main(int argc, char **argv)
  9. {
  10.  
  11.     //-----------------------------------------
  12.     // Declare and initialize variables
  13.     WSADATA wsaData;
  14.     int iResult;
  15.  
  16.     DWORD dwError;
  17.  
  18.     struct hostent *remoteHost;
  19.     char *host_name;
  20.     struct in_addr addr;
  21.  
  22.     // Initialize Winsock
  23.     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  24.     if (iResult != 0)
  25.     {
  26.         printf("WSAStartup failed: %d\n", iResult);
  27.         return 1;
  28.     }
  29.  
  30.     host_name = "www.onet.pl";
  31.  
  32.  
  33.     printf("Calling gethostbyname with %s\n", host_name);
  34.     remoteHost = gethostbyname(host_name);
  35.  
  36.  
  37.     if (remoteHost == NULL)
  38.     {
  39.         dwError = WSAGetLastError();
  40.         if (dwError != 0) {
  41.             if (dwError == WSAHOST_NOT_FOUND) {
  42.                 printf("Host not found\n");
  43.                 return 1;
  44.             }
  45.             else if (dwError == WSANO_DATA) {
  46.                 printf("No data record found\n");
  47.                 return 1;
  48.             }
  49.             else {
  50.                 printf("Function failed with error: %ld\n", dwError);
  51.                 return 1;
  52.             }
  53.         }
  54.     }
  55.     else
  56.     {
  57.         printf("Function returned:\n");
  58.         printf("\tOfficial name: %s\n", remoteHost->h_name);
  59.         printf("\tAlternate names: %s\n", remoteHost->h_aliases);
  60.         printf("\tAddress type: ");
  61.         switch (remoteHost->h_addrtype) {
  62.         case AF_INET:
  63.             printf("AF_INET\n");
  64.             break;
  65.         case AF_INET6:
  66.             printf("AF_INET\n");
  67.             break;
  68.         case AF_NETBIOS:
  69.             printf("AF_NETBIOS\n");
  70.             break;
  71.         default:
  72.             printf(" %d\n", remoteHost->h_addrtype);
  73.             break;
  74.         }
  75.         printf("\tAddress length: %d\n", remoteHost->h_length);
  76.         addr.s_addr = *(u_long *)remoteHost->h_addr_list[0];
  77.         printf("\tFirst IP Address: %s\n", inet_ntoa(addr));
  78.     }
  79.     getchar();
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement