/* * A small test for getaddrinfo * Copyright (C) 2007 Kai Blin * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include #ifdef __GNU__ #include #include #include #include #include #include #include #include #else #include #include #endif #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif int main(int argc, char **argv) { char hostname[HOST_NAME_MAX]; struct hostent *he; struct addrinfo *ai, *curr_ai; struct ifaddrs *ifa, *curr_ifa; int ret; if(gethostname(hostname, HOST_NAME_MAX)) { perror("gethostname:"); return 1; } printf("Hostname according to gethostname() is '%s'\n", hostname); if((he = gethostbyname(hostname)) == NULL) { /*herror("gethostbyname:");*/ return 1; } printf("Hostname according to gethostbyname() is '%s'\n", he->h_name); printf("\tlen is %d\n", he->h_length); if(he->h_addrtype == AF_INET) { int count = 0; struct in_addr addr; while(he->h_addr_list[count]) { memcpy(&addr, he->h_addr_list[count], he->h_length); printf("\tip address is %s\n", inet_ntoa(addr)); printf("\t\the->h_addr_list[%d][0] is %d\n", count, he->h_addr_list[count][0]); ++count; } } if((ret = getaddrinfo(hostname, NULL, NULL, &ai)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(ret)); return 1; } for(curr_ai = ai; curr_ai != NULL; curr_ai = curr_ai->ai_next) { printf("Hostname according to getaddrinfo() is '%s'\n", curr_ai->ai_canonname); if(curr_ai->ai_family == AF_INET) { struct in_addr addr = ((struct sockaddr_in *)curr_ai->ai_addr)->sin_addr; printf("\tip address is %s\n", inet_ntoa(addr)); } } freeaddrinfo(ai); #ifdef __GNU__ if(getifaddrs(&ifa) < 0 ) { perror("getifaddrs"); return 1; } for(curr_ifa = ifa; curr_ifa != NULL; curr_ifa = curr_ifa->ifa_next) { printf("Interface according to getifaddrs() is '%s'\n", curr_ifa->ifa_name); if(curr_ifa->ifa_addr->sa_family == AF_INET) { struct in_addr addr = ((struct sockaddr_in *)curr_ifa->ifa_addr)->sin_addr; printf("\tip address is %s\n", inet_ntoa(addr)); } printf("\tflags: 0x%08x\n", curr_ifa->ifa_flags); } freeifaddrs(ifa); #endif return 0; }