OSDN Git Service

VER0.1.4
[lib1stclass/main.git] / host2ip.c
1 /*
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright: 2010- 1stclass.co.jp.  All rights reserved.
5 *
6 * Created by Hajime Kurita
7 */
8 #include <stdio.h>
9 #include <string.h>
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <arpa/inet.h>
13 #include <netdb.h>
14
15 #ifdef __cplusplus
16 #include "1stclass.hpp"
17 #include<iostream>a
18 #include<string>
19 string firstclass::host2ip(const string server_str){
20   char ip[32]="";
21   char *server=NULL;
22   try{
23     server=new char[sizeof(char)*(server_str.length()+1)];
24     server[0]='\0';
25     safe_strcat(server, server_str.c_str(), sizeof(char)*(server_str.length()+1));
26 #else
27 #include "1stclass.h"
28 int host2ip(const char *server, char *ip){
29 #endif
30   struct addrinfo hint, *res, *p;
31   int error=0;
32   char ipstr[INET6_ADDRSTRLEN];
33   
34   memset(&hint, 0, sizeof(hint));
35   hint.ai_family = PF_INET;
36   hint.ai_socktype = SOCK_STREAM;
37
38   error = getaddrinfo(server, "http", &hint, &res);
39
40   if(error){
41     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
42
43 #ifdef __cplusplus
44     delete[] server;
45     return "";
46 #else
47     return 1;
48 #endif
49   }
50   
51   for(p = res;p != NULL; p = p->ai_next) {
52     void *addr;
53     char *ipver;
54     
55     if (p->ai_family == AF_INET) { // IPv4
56       struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
57       addr = &(ipv4->sin_addr);
58       ipver = "IPv4";
59     } else { // IPv6
60       struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
61       addr = &(ipv6->sin6_addr);
62       ipver = "IPv6";
63     }
64     
65     // convert the IP to a string and print it:
66     inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
67   }
68   freeaddrinfo(res); // free the linked list
69   
70 #ifdef __cplusplus
71     delete[] server;
72     firstclass::safe_strcat(ip, ipstr, sizeof(ip));
73     string last_ip(ip);
74     return last_ip;
75   }
76   catch(...){
77     if(server!=NULL)
78       delete[] server;
79     return "";
80   }
81 #else
82   safe_strcat(ip, ipstr, sizeof(ip));
83   return 0;
84 #endif
85 }