summaryrefslogtreecommitdiffstats
path: root/net/quic/quic_socket_address_coder.cc
blob: 3d0031d188f8b92d33fd18e0c39a62edf3301627 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/quic/quic_socket_address_coder.h"

#include "net/base/sys_addrinfo.h"

using std::string;

namespace net {

namespace {

// For convenience, the values of these constants match the values of AF_INET
// and AF_INET6 on Linux.
const uint16 kIPv4 = 2;
const uint16 kIPv6 = 10;

}  // namespace

QuicSocketAddressCoder::QuicSocketAddressCoder() {}

QuicSocketAddressCoder::QuicSocketAddressCoder(const IPEndPoint& address)
    : address_(address) {}

QuicSocketAddressCoder::~QuicSocketAddressCoder() {}

string QuicSocketAddressCoder::Encode() const {
  string serialized;
  uint16 address_family;
  switch (address_.GetSockAddrFamily()) {
    case AF_INET:
      address_family = kIPv4;
      break;
    case AF_INET6:
      address_family = kIPv6;
      break;
    default:
      return serialized;
  }
  serialized.append(reinterpret_cast<const char*>(&address_family),
                    sizeof(address_family));
  serialized.append(IPAddressToPackedString(address_.address()));
  uint16 port = address_.port();
  serialized.append(reinterpret_cast<const char*>(&port), sizeof(port));
  return serialized;
}

bool QuicSocketAddressCoder::Decode(const char* data, size_t length) {
  uint16 address_family;
  if (length < sizeof(address_family)) {
    return false;
  }
  memcpy(&address_family, data, sizeof(address_family));
  data += sizeof(address_family);
  length -= sizeof(address_family);

  size_t ip_length;
  switch (address_family) {
    case kIPv4:
      ip_length = kIPv4AddressSize;
      break;
    case kIPv6:
      ip_length = kIPv6AddressSize;
      break;
    default:
      return false;
  }
  if (length < ip_length) {
    return false;
  }
  IPAddressNumber ip(ip_length);
  memcpy(&ip[0], data, ip_length);
  data += ip_length;
  length -= ip_length;

  uint16 port;
  if (length != sizeof(port)) {
    return false;
  }
  memcpy(&port, data, length);

  address_ = IPEndPoint(ip, port);
  return true;
}

}  // namespace net