OSDN Git Service

VER0.1.0
[lib1stclass/main.git] / host2ip.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <netdb.h>
7
8 #ifdef __cplusplus
9 #include "1stclass.hpp"
10 string firstclass::host2ip(const string server_str){
11   char ip[32]="";
12   char server[128]="";
13   safe_strcat(server, server_str.c_str());
14 #else
15 #include "lib1stclass.h"
16 int host2ip(const char *server, char *ip){
17 #endif
18
19   struct addrinfo hint, *res, *p;
20   int error=0;
21   char ipstr[INET6_ADDRSTRLEN];
22   
23   memset(&hint, 0, sizeof(hint));
24   hint.ai_family = PF_INET;
25   hint.ai_socktype = SOCK_STREAM;
26
27   error = getaddrinfo(server, "http", &hint, &res);
28
29   if(error){
30     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
31
32 #ifdef __cplusplus
33     return "";
34 #else
35     return 1;
36 #endif
37   }
38   
39   for(p = res;p != NULL; p = p->ai_next) {
40     void *addr;
41     char *ipver;
42     
43     if (p->ai_family == AF_INET) { // IPv4
44       struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
45       addr = &(ipv4->sin_addr);
46       ipver = "IPv4";
47     } else { // IPv6
48       struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
49       addr = &(ipv6->sin6_addr);
50       ipver = "IPv6";
51     }
52     
53     // convert the IP to a string and print it:
54     inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
55   }
56   freeaddrinfo(res); // free the linked list
57   
58 #ifdef __cplusplus
59   firstclass::safe_strcat(ip, ipstr);
60   string last_ip(ip);
61   return last_ip;
62 #else
63   safe_strcat(ip, ipstr);
64   return 0;
65 #endif
66
67 }