Last bits of the merger.
[tinc] / src / netutl.c
1 /*
2     netutl.c -- some supporting network utility code
3     Copyright (C) 1998-2002 Ivo Timmermans <itimmermans@bigfoot.com>
4                   2000-2002 Guus Sliepen <guus@sliepen.warande.net>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: netutl.c,v 1.12.4.23 2002/02/11 10:16:18 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <fcntl.h>
26 #include <netdb.h>
27 #include <netinet/in.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/socket.h>
32 #include <syslog.h>
33 #include <arpa/inet.h>
34
35 #include <utils.h>
36 #include <xalloc.h>
37
38 #include "errno.h"
39 #include "conf.h"
40 #include "net.h"
41 #include "netutl.h"
42
43 #include "system.h"
44
45 char *hostlookup(unsigned long addr)
46 {
47   char *name;
48   struct hostent *host = NULL;
49   struct in_addr in;
50   int lookup_hostname = 0;
51 cp
52   in.s_addr = addr;
53
54   get_config_bool(lookup_config(config_tree, "Hostnames"), &lookup_hostname);
55
56   if(lookup_hostname)
57     host = gethostbyaddr((char *)&in, sizeof(in), AF_INET);
58
59   if(!lookup_hostname || !host)
60     {
61       asprintf(&name, "%s", inet_ntoa(in));
62     }
63   else
64     {
65       asprintf(&name, "%s", host->h_name);
66     }
67 cp
68   return name;
69 }
70
71 /*
72   Turn a string into an IP address
73   return NULL on failure
74   Should support IPv6 and other stuff in the future.
75 */
76 ipv4_t str2address(char *str)
77 {
78   ipv4_t address;
79   struct hostent *h;
80 cp
81   if(!(h = gethostbyname(str)))
82     {
83       if(debug_lvl >= DEBUG_ERROR)
84         syslog(LOG_WARNING, _("Error looking up `%s': %s\n"), str, strerror(errno));
85         
86       return 0;
87     }
88
89   address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
90 cp
91   return address;
92 }
93
94 char *address2str(ipv4_t address)
95 {
96   char *str;
97 cp
98   asprintf(&str, "%hu.%hu.%hu.%hu",
99            (unsigned short int)((address >> 24) & 255),
100            (unsigned short int)((address >> 16) & 255),
101            (unsigned short int)((address >> 8) & 255),
102            (unsigned short int)(address & 255));
103 cp
104   return str;
105 }