9aa4620bd82c5e7dee61621d5f51514f60a32e47
[sahlberg/ctdb.git] / common / system_common.c
1 /* 
2    ctdb system specific code to manage raw sockets on linux
3
4    Copyright (C) Ronnie Sahlberg  2007
5    Copyright (C) Andrew Tridgell  2007
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "system/network.h"
23
24 /*
25   uint16 checksum for n bytes
26  */
27 uint32_t uint16_checksum(uint16_t *data, size_t n)
28 {
29         uint32_t sum=0;
30         while (n>=2) {
31                 sum += (uint32_t)ntohs(*data);
32                 data++;
33                 n -= 2;
34         }
35         if (n == 1) {
36                 sum += (uint32_t)ntohs(*(uint8_t *)data);
37         }
38         return sum;
39 }
40
41 /*
42   see if we currently have an interface with the given IP
43
44   we try to bind to it, and if that fails then we don't have that IP
45   on an interface
46  */
47 bool ctdb_sys_have_ip(ctdb_sock_addr *_addr)
48 {
49         int s;
50         int ret;
51         ctdb_sock_addr __addr = *_addr;
52         ctdb_sock_addr *addr = &__addr;
53
54         switch (addr->sa.sa_family) {
55         case AF_INET:
56                 addr->ip.sin_port = 0;
57                 break;
58         case AF_INET6:
59                 addr->ip6.sin6_port = 0;
60                 break;
61         }
62
63         s = socket(addr->sa.sa_family, SOCK_STREAM, IPPROTO_TCP);
64         if (s == -1) {
65                 return false;
66         }
67
68         ret = bind(s, (struct sockaddr *)addr, sizeof(ctdb_sock_addr));
69
70         close(s);
71         return ret == 0;
72 }