Some very small fixes
[oweals/tinc.git] / src / netutl.c
1 /*
2     netutl.c -- some supporting network utility code
3     Copyright (C) 1998-2001 Ivo Timmermans <itimmermans@bigfoot.com>
4                   2000,2001 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.21 2001/10/31 20:37:54 guus Exp $
21 */
22
23 #include "config.h"
24
25 #include <arpa/inet.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
34 #include <utils.h>
35 #include <xalloc.h>
36
37 #include "errno.h"
38 #include "conf.h"
39 #include "net.h"
40 #include "netutl.h"
41
42 #include "system.h"
43
44 char *hostlookup(unsigned long addr)
45 {
46   char *name;
47   struct hostent *host = NULL;
48   struct in_addr in;
49   int lookup_hostname = 0;
50 cp
51   in.s_addr = addr;
52
53   get_config_bool(lookup_config(config_tree, "Hostnames"), &lookup_hostname);
54
55   if(lookup_hostname)
56     host = gethostbyaddr((char *)&in, sizeof(in), AF_INET);
57
58   if(!lookup_hostname || !host)
59     {
60       asprintf(&name, "%s", inet_ntoa(in));
61     }
62   else
63     {
64       asprintf(&name, "%s", host->h_name);
65     }
66 cp
67   return name;
68 }
69
70 /*
71   Turn a string into an IP addy with netmask
72   return NULL on failure
73 */
74 ip_mask_t *strtoip(char *str)
75 {
76   ip_mask_t *ip;
77   int masker;
78   char *q, *p;
79   struct hostent *h;
80 cp
81   p = str;
82   if((q = strchr(p, '/')))
83     {
84       *q = '\0';
85       q++; /* q now points to netmask part, or NULL if no mask */
86     }
87
88   if(!(h = gethostbyname(p)))
89     {
90       if(debug_lvl >= DEBUG_ERROR)
91         syslog(LOG_WARNING, _("Error looking up `%s': %s\n"), p, strerror(errno));
92         
93       return NULL;
94     }
95
96   masker = 0;
97   if(q)
98     {
99       masker = strtol(q, &p, 10);
100       if(q == p || (*p))
101         return NULL;
102     }
103
104   ip = xmalloc(sizeof(*ip));
105   ip->address = ntohl(*((ipv4_t*)(h->h_addr_list[0])));
106
107   ip->mask = masker ? ~((1 << (32 - masker)) - 1) : 0;
108 cp
109   return ip;
110 }
111