Goby v2
ip_codecs.cpp
1 // Copyright 2009-2018 Toby Schneider (http://gobysoft.org/index.wt/people/toby)
2 // GobySoft, LLC (2013-)
3 // Massachusetts Institute of Technology (2007-2014)
4 // Community contributors (see AUTHORS file)
5 //
6 //
7 // This file is part of the Goby Underwater Autonomy Project Libraries
8 // ("The Goby Libraries").
9 //
10 // The Goby Libraries are free software: you can redistribute them and/or modify
11 // them under the terms of the GNU Lesser General Public License as published by
12 // the Free Software Foundation, either version 2.1 of the License, or
13 // (at your option) any later version.
14 //
15 // The Goby Libraries are distributed in the hope that they will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public License
21 // along with Goby. If not, see <http://www.gnu.org/licenses/>.
22 
23 #include "ip_codecs.h"
24 
25 #include <arpa/inet.h>
26 #include <netinet/in.h>
27 
28 dccl::uint32 goby::acomms::IPv4AddressCodec::pre_encode(const std::string& field_value)
29 {
30  in_addr addr;
31  int ret = inet_aton(field_value.c_str(), &addr);
32  return (ret == 0) ? -1 : addr.s_addr;
33 }
34 std::string goby::acomms::IPv4AddressCodec::post_decode(const dccl::uint32& wire_value)
35 {
36  in_addr addr;
37  addr.s_addr = wire_value;
38  return std::string(inet_ntoa(addr));
39 }
40 
41 uint16_t goby::acomms::net_checksum(const std::string& data)
42 {
43  uint32_t sum = 0;
44  int len = data.size();
45  uint16_t* p = (uint16_t*)&data[0];
46 
47  while (len > 1)
48  {
49  sum += ntohs(*(p++));
50  len -= 2;
51  }
52 
53  // last byte is large byte (LSB is padded with zeros)
54  if (len)
55  sum += (*(uint8_t*)p << 8) & 0xFF00;
56 
57  while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16);
58 
59  return ~sum;
60 }