/* webresolve.c Copyright (C) 2000-2002 Ulric Eriksson 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, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include #include #include #include #include #include #include #include #include /* The cache is implemented as a linked list, based on the assumption that we will usually want to get the most recently inserted items. */ typedef struct ip_cache { char *ip; char *host; struct ip_cache *next; } ip_cache; static ip_cache *cache = NULL; static void *mmalloc(size_t n) { void *p = malloc(n); if (!p) { fprintf(stderr, "Can't allocate %ld bytes\n", (long)n); exit(1); } return p; } static ip_cache *lookup_ip(char *ip) { ip_cache *c; for (c = cache; c; c = c->next) if (!strcmp(ip, c->ip)) return c; return NULL; } static char *reverse_lookup(char *ip) { char *host; struct hostent *hp; #ifdef HAVE_INET_ATON struct in_addr in; #endif ip_cache *c; if (!isdigit((int)*ip)) return ip; c = lookup_ip(ip); if (c) return c->host; #ifdef HAVE_INET_ATON inet_aton(ip, &in); hp = gethostbyaddr((char *)&in.s_addr, sizeof(in.s_addr), AF_INET); #else hp = gethostbyname(ip); hp = gethostbyaddr(hp->h_addr, hp->h_length, AF_INET); #endif if (hp) host = hp->h_name; else host = ip; c = mmalloc(sizeof *c); c->host = mmalloc(strlen(host)+1); c->ip = mmalloc(strlen(ip)+1); strcpy(c->host, host); strcpy(c->ip, ip); c->next = cache; cache = c; return c->host; } int main(void) { char b[1024], ip[1024], rest[1024]; while (fgets(b, sizeof b, stdin)) { sscanf(b, "%s %[^\n]", ip, rest); printf("%s %s\n", reverse_lookup(ip), rest); } return 0; }