1: #include <sys/socket.h>
2: #include <netdb.h>
3: #include <arpa/inet.h>
4: #include <err.h>
5: #define OUTSTR_SIZE 4096
6: extern "C"
7: {
8: const char* copyStr( const char* str )
9: {
10: char* s = (char*)malloc(strlen(str) + 1);
11: strcpy(s, str);
12: return s;
13: }
14: const char* IOSGetAddressInfo(const char *host )
15: {
16: if( NULL == host )
17: return copyStr("ERROR_HOSTNULL");
18: char outstr[OUTSTR_SIZE];
19: struct addrinfo hints, *res, *res0;
20: memset(&hints, 0, sizeof(hints));
21: hints.ai_family = PF_UNSPEC;
22: hints.ai_socktype = SOCK_STREAM;
23: hints.ai_flags = AI_DEFAULT;
24: printf("getaddrinfo: %s\n", host);
25: int error = getaddrinfo(host, "http", &hints, &res0);
26: if (error != 0 )
27: {
28: printf("getaddrinfo: %s\n", gai_strerror(error));
29: return copyStr("ERROR_GETADDR");
30: }
31: memset( outstr, 0, sizeof(char)*OUTSTR_SIZE );
32: struct sockaddr_in6* addr6;
33: struct sockaddr_in* addr;
34: const char* solvedaddr;
35: char ipbuf[32];
36: for (res = res0; res; res = res->ai_next)
37: {
38: if (res->ai_family == AF_INET6)
39: {
40: addr6 =( struct sockaddr_in6*)res->ai_addr;
41: solvedaddr = inet_ntop(AF_INET6, &addr6->sin6_addr, ipbuf, sizeof(ipbuf));
42: strcat ( outstr, "ipv6|");
43: strcat ( outstr, solvedaddr);
44: }
45: else
46: {
47: addr =( struct sockaddr_in*)res->ai_addr;
48: solvedaddr = inet_ntop(AF_INET, &addr->sin_addr, ipbuf, sizeof(ipbuf));
49: strcat ( outstr, "ipv4|");
50: strcat ( outstr, solvedaddr);
51: }
52: strcat ( outstr, "|");
53: }
54: return copyStr(outstr);
55: }
56: }
转载请注明:http://www.cppblog.com/sunicdavy战魂小筑