| 1 | #include <stdio.h>
|
|---|
| 2 | #include <stdlib.h>
|
|---|
| 3 | #include <errno.h>
|
|---|
| 4 | #include <winsock2.h>
|
|---|
| 5 | #include <sys/types.h>
|
|---|
| 6 |
|
|---|
| 7 | static LPSTR PrintError(int ErrorCode);
|
|---|
| 8 |
|
|---|
| 9 | int main(int argc, char *argv[])
|
|---|
| 10 | {
|
|---|
| 11 | // Enable WinSock2
|
|---|
| 12 | WORD wVersionRequested;
|
|---|
| 13 | wVersionRequested = MAKEWORD( 2, 2 );
|
|---|
| 14 |
|
|---|
| 15 | WSADATA wsaData;
|
|---|
| 16 | int rc;
|
|---|
| 17 | rc = WSAStartup( wVersionRequested, &wsaData );
|
|---|
| 18 | if (rc != 0)
|
|---|
| 19 | {
|
|---|
| 20 | fprintf(stderr, "Cannot find an usable WinSock2 dll");
|
|---|
| 21 | exit(1);
|
|---|
| 22 | }
|
|---|
| 23 |
|
|---|
| 24 | // Check the command line
|
|---|
| 25 | if(argc != 2)
|
|---|
| 26 | {
|
|---|
| 27 | fprintf(stderr, "Usage: %s hostname\n", argv[0]);
|
|---|
| 28 | exit(1);
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | // Get the host info
|
|---|
| 32 | struct hostent *hostent;
|
|---|
| 33 | char *host = argv[1];
|
|---|
| 34 | if((hostent = gethostbyname(host)) == NULL)
|
|---|
| 35 | {
|
|---|
| 36 | fprintf(stderr, "gethostbyname() failed with error %d: %s\n",
|
|---|
| 37 | WSAGetLastError(), PrintError(WSAGetLastError()));
|
|---|
| 38 | exit(1);
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | // Print to output
|
|---|
| 42 | printf("Hostname: %s\n", hostent->h_name);
|
|---|
| 43 | printf("IP Address: %s\n", inet_ntoa(*((struct in_addr *)hostent->h_addr)));
|
|---|
| 44 |
|
|---|
| 45 | return 0;
|
|---|
| 46 | }
|
|---|
| 47 |
|
|---|
| 48 | LPSTR PrintError(int ErrorCode)
|
|---|
| 49 | {
|
|---|
| 50 | static char Message[1024];
|
|---|
| 51 |
|
|---|
| 52 | // If this program was multithreaded, we'd want to use
|
|---|
| 53 | // FORMAT_MESSAGE_ALLOCATE_BUFFER instead of a static buffer here.
|
|---|
| 54 | // (And of course, free the buffer when we were done with it)
|
|---|
| 55 |
|
|---|
| 56 | FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
|
|---|
| 57 | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, ErrorCode,
|
|---|
| 58 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
|---|
| 59 | (LPWSTR) Message, 1024, NULL);
|
|---|
| 60 | return Message;
|
|---|
| 61 | }
|
|---|