IBR-DTNSuite  0.12
StreamContactHeader.cpp
Go to the documentation of this file.
1 /*
2  * StreamContactHeader.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "ibrdtn/config.h"
24 #include "ibrdtn/data/Bundle.h"
25 #include "ibrdtn/data/Exceptions.h"
27 #include <typeinfo>
28 
29 #ifdef __WIN32__
30 #include <winsock2.h>
31 #else
32 #include <netinet/in.h>
33 #endif
34 
35 namespace dtn
36 {
37  namespace streams
38  {
40  : _flags(REQUEST_ACKNOWLEDGMENTS), _keepalive(0)
41  {
42  }
43 
45  : _localeid(localeid), _flags(REQUEST_ACKNOWLEDGMENTS), _keepalive(0)
46  {
47  }
48 
50  {
51  }
52 
54  {
55  _localeid = other._localeid;
56  _flags = other._flags;
57  _keepalive = other._keepalive;
58  return *this;
59  }
60 
62  {
63  return _localeid;
64  }
65 
66  std::ostream &operator<<(std::ostream &stream, const StreamContactHeader &h)
67  {
68  //BundleStreamWriter writer(stream);
69  stream << "dtn!" << TCPCL_VERSION << h._flags.get<char>();
70 
71  // convert to network byte order
72  uint16_t ka = htons(h._keepalive);
73  stream.write( (char*)&ka, 2 );
74 
76  stream << eid;
77 
78  return stream;
79  }
80 
81  std::istream &operator>>(std::istream &stream, StreamContactHeader &h)
82  {
83  char magic[5];
84 
85  // wait for magic
86  stream.read(magic, 4); magic[4] = '\0';
87  string str_magic(magic);
88 
89  if (str_magic != "dtn!")
90  {
91  throw InvalidProtocolException("not talking dtn");
92  }
93 
94  // version
95  char version; stream.get(version);
96  if (version != TCPCL_VERSION)
97  {
98  throw InvalidProtocolException("invalid bundle protocol version");
99  }
100 
101  // flags
102  char tmp;
103  stream.get(tmp);
104  h._flags = tmp;
105 
106  uint16_t ka = 0;
107  stream.read((char*)&ka, 2);
108 
109  // convert from network byte order
110  h._keepalive = ntohs(ka);
111 
113  stream >> eid;
114  h._localeid = EID(eid);
115 
116  return stream;
117  }
118  }
119 }