| 1 | #include <stdio.h>
|
|---|
| 2 | #include <stdlib.h>
|
|---|
| 3 | #include <errno.h>
|
|---|
| 4 | #include <Ws2tcpip.h>
|
|---|
| 5 | #include <sys/types.h>
|
|---|
| 6 |
|
|---|
| 7 | int main(int argc, char *argv[])
|
|---|
| 8 | {
|
|---|
| 9 | if (argc != 2)
|
|---|
| 10 | {
|
|---|
| 11 | fprintf(stderr, "Usage: %s hostname\n", argv[0]);
|
|---|
| 12 | return 1;
|
|---|
| 13 | }
|
|---|
| 14 |
|
|---|
| 15 | // Enable WinSock2
|
|---|
| 16 | WORD wVersionRequested;
|
|---|
| 17 | wVersionRequested = MAKEWORD( 2, 2 );
|
|---|
| 18 |
|
|---|
| 19 | WSADATA wsaData;
|
|---|
| 20 | int rc;
|
|---|
| 21 | rc = WSAStartup( wVersionRequested, &wsaData );
|
|---|
| 22 | if (rc != 0)
|
|---|
| 23 | {
|
|---|
| 24 | fprintf(stderr, "Cannot find an usable WinSock2 dll");
|
|---|
| 25 | exit(1);
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | struct addrinfo hints;
|
|---|
| 29 | memset(&hints, 0, sizeof hints);
|
|---|
| 30 | hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
|
|---|
| 31 | hints.ai_socktype = SOCK_STREAM;
|
|---|
| 32 |
|
|---|
| 33 | struct addrinfo *results;
|
|---|
| 34 | if ((rc = getaddrinfo(argv[1], NULL, &hints, &results)) != 0)
|
|---|
| 35 | {
|
|---|
| 36 | fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
|
|---|
| 37 | WSACleanup();
|
|---|
| 38 | return 2;
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | struct addrinfo *result;
|
|---|
| 42 | for(result = results; result != NULL; result = result->ai_next)
|
|---|
| 43 | {
|
|---|
| 44 | void *addr;
|
|---|
| 45 |
|
|---|
| 46 | switch (result->ai_family)
|
|---|
| 47 | {
|
|---|
| 48 | case AF_INET:
|
|---|
| 49 | {
|
|---|
| 50 | sockaddr_in *sockaddr_in = (struct sockaddr_in *)result->ai_addr;
|
|---|
| 51 | printf("Hostname: %s\n", argv[1]);
|
|---|
| 52 | printf("IP Address: %s\n", inet_ntoa(sockaddr_in->sin_addr));
|
|---|
| 53 | break;
|
|---|
| 54 | }
|
|---|
| 55 | case AF_INET6:
|
|---|
| 56 | {
|
|---|
| 57 | struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)result->ai_addr;
|
|---|
| 58 | addr = &(ipv6->sin6_addr);
|
|---|
| 59 |
|
|---|
| 60 | /* convert the IP to a string and print it: */
|
|---|
| 61 | char ipstr[INET6_ADDRSTRLEN];
|
|---|
| 62 | inet_ntop(result->ai_family, addr, ipstr, sizeof ipstr);
|
|---|
| 63 |
|
|---|
| 64 | printf("Hostname: %s\n", argv[1]);
|
|---|
| 65 | printf("IP Address: %s\n", ipstr);
|
|---|
| 66 | break;
|
|---|
| 67 | }
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | // Just print the first address
|
|---|
| 71 | break;
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | freeaddrinfo(results); // free the linked list
|
|---|
| 75 |
|
|---|
| 76 | WSACleanup();
|
|---|
| 77 | return 0;
|
|---|
| 78 | }
|
|---|