/ src / libserver / cm_ip.cpp
cm_ip.cpp
 1  /*
 2      EIBD eib bus access and management daemon
 3      Copyright (C) 2005-2011 Martin Koegler <mkoegler@auto.tuwien.ac.at>
 4  
 5      This program is free software; you can redistribute it and/or modify
 6      it under the terms of the GNU General Public License as published by
 7      the Free Software Foundation; either version 2 of the License, or
 8      (at your option) any later version.
 9  
10      This program is distributed in the hope that it will be useful,
11      but WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13      GNU General Public License for more details.
14  
15      You should have received a copy of the GNU General Public License
16      along with this program; if not, write to the Free Software
17      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19  
20  #include "cm_ip.h"
21  #include "config.h"
22  
23  #include <net/if.h>
24  #include <netinet/in.h>
25  #include <netdb.h>
26  #include <sys/socket.h>
27  #include <unistd.h>
28  
29  CArray
30  IPtoEIBNetIP (const struct sockaddr_in * a, bool nat, uint8_t protocol)
31  {
32    CArray buf;
33    buf.resize (8);
34    buf[0] = 0x08;
35    buf[1] = protocol;
36    if (nat)
37      {
38        buf[2] = 0;
39        buf[3] = 0;
40        buf[4] = 0;
41        buf[5] = 0;
42        buf[6] = 0;
43        buf[7] = 0;
44      }
45    else
46      {
47        buf[2] = (ntohl (a->sin_addr.s_addr) >> 24) & 0xff;
48        buf[3] = (ntohl (a->sin_addr.s_addr) >> 16) & 0xff;
49        buf[4] = (ntohl (a->sin_addr.s_addr) >> 8) & 0xff;
50        buf[5] = (ntohl (a->sin_addr.s_addr) >> 0) & 0xff;
51        buf[6] = (ntohs (a->sin_port) >> 8) & 0xff;
52        buf[7] = (ntohs (a->sin_port) >> 0) & 0xff;
53      }
54    return buf;
55  }
56  
57  bool
58  EIBnettoIP (const CArray & buf, struct sockaddr_in *a,
59              const struct sockaddr_in *src, bool & nat, uint8_t protocol)
60  {
61    int ip, port;
62    memset (a, 0, sizeof (*a));
63    if (buf[0] != 0x8 || buf[1] != protocol)
64      return true;
65    ip = (buf[2] << 24) | (buf[3] << 16) | (buf[4] << 8) | (buf[5]);
66    port = (buf[6] << 8) | (buf[7]);
67  #ifdef HAVE_SOCKADDR_IN_LEN
68    a->sin_len = sizeof (*a);
69  #endif
70    a->sin_family = AF_INET;
71    if (port == 0)
72      a->sin_port = src->sin_port;
73    else
74      a->sin_port = htons (port);
75    if (ip == 0)
76      {
77        nat = true;
78        a->sin_addr.s_addr = src->sin_addr.s_addr;
79      }
80    else
81      a->sin_addr.s_addr = htonl (ip);
82  
83    return false;
84  }