b214fc325cc89d91e2ea41974564c8c6bc82ce24
[senf.git] / senf / Socket / Protocols / INet / INet4Address.hh
1 // $Id$
2 //
3 // Copyright (C) 2007
4 // Fraunhofer Institute for Open Communication Systems (FOKUS)
5 // Competence Center NETwork research (NET), St. Augustin, GERMANY
6 //     Stefan Bund <g0dil@berlios.de>
7 //
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 2 of the License, or
11 // (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the
20 // Free Software Foundation, Inc.,
21 // 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
23 /** \file
24     \brief INet4Address public header */
25
26 #ifndef HH_SENF_Socket_Protocols_INet_INet4Address_
27 #define HH_SENF_Socket_Protocols_INet_INet4Address_ 1
28
29 // Custom includes
30 #include <iostream>
31 #include <string>
32 #include <boost/cstdint.hpp>
33 #include <boost/array.hpp>
34 #include <boost/operators.hpp>
35 #include <senf/Utils/safe_bool.hh>
36 #include <senf/Utils/Tags.hh>
37
38 //#include "INet4Address.mpp"
39 ///////////////////////////////hh.p////////////////////////////////////////
40
41 namespace senf {
42
43     /** \brief IPv4 Internet address
44
45         INet4Address represents a simple IP address. It is modelled as a fixed-size
46         container/sequence of 4 bytes.
47
48         The following statements all create the same INet4 address <code>211.194.177.160</code>
49         \code
50         // Used to construct constant INet4 addresses
51         INet4Address(0xD3C2B1A0)
52
53         // Construct an INet4 address from it's string representation. All the standard address
54         // representations are supported
55         INet4Address::from_string("211.194.177.160")
56         INet4Address::from_string("211.12759456")
57
58         // Construct an INet4 address from raw data. 'from_data' takes an arbitrary iterator (e.g. a
59         // pointer) as argument. Here we use a fixed array but normally you will need this to build
60         // an INet4 address in a packet parser
61         char rawBytes[] = { 0xD3, 0xC2, 0xB1, 0xA0 };
62         INet4Address::from_data(rawBytes)
63
64         // Construct an INet4 address from the standard POSIX representation: a 32-bit integer in
65         // network byte oder. This is used to interface with POSIX routines
66         struct sockaddr_in saddr = ...;
67         INet4Address::from_inaddr(saddr.sin_addr.s_addr)
68         \endcode
69
70         Since INet4Address is based on \c boost::array, you can access the raw data bytes of the
71         address (in network byte order) using \c begin(), \c end() or \c operator[]
72         \code
73         INet4Address ina = ...;
74         Packet::iterator i = ...;
75         std::copy(ina.begin(), ina.end(), i); // Copies 4 bytes
76         \endcode
77
78         \see CheckINet4Network \n INet4Network
79
80         \implementation We awkwardly need to use static named constructors (<tt>from_</tt> members)
81             instead of ordinarily overloaded constructors for one simple reason: <tt>char *</tt>
82             doubles as string literal and as arbitrary data iterator. The iterator constructor can
83             therefore not be distinguished from initialization with a string literal. Therefore we
84             need to disambiguate using the named constructors.
85
86         \ingroup addr_group
87       */
88     class INet4Address
89         : public boost::array<boost::uint8_t,4>,
90           public comparable_safe_bool<INet4Address>
91     {
92     public:
93         ///////////////////////////////////////////////////////////////////////////
94         // Types
95
96         typedef uint32_t address_type;  ///< Address representation as number in host byte order
97         typedef uint32_t inaddr_type;   ///< Legacy address representation in network byte order
98
99         static INet4Address const None; ///< The empty (0) address
100         static INet4Address const Loopback; ///< The loopback (127.0.0.1) address
101         static INet4Address const Broadcast; ////< The global broadcast (255.255.255.255) address
102
103         ///////////////////////////////////////////////////////////////////////////
104         ///\name Structors and default members
105         ///@{
106
107         INet4Address();                 ///< Construct an empty address
108         explicit INet4Address(senf::NoInit_t); ///< Construct uninitialized (!) address
109         explicit INet4Address(address_type value);
110                                         ///< Construct an address constant
111
112         static INet4Address from_string(std::string const & s);
113                                         ///< Convert string to address
114                                         /**< This member will try to convert the given string into
115                                              an IP address. from_string() supports all standard IP
116                                              literal representations as well as hostnames.
117                                              \attention This call may block if \a s represents a
118                                                  hostname which must be looked up via some network
119                                                  protocol like DNS or NIS
120                                              \throws AddressSyntaxException if the address cannot be
121                                                  converted for some reason
122                                              \param[in] s Address literal or hostname */
123
124         template <class InputIterator>
125         static INet4Address from_data(InputIterator i);
126                                         ///< Construct address from 4 bytes of raw data
127                                         /**< from_data will build an address from 4 bytes of raw
128                                              data as accessed by the iterator. The data must be in
129                                              network byte order. */
130         static INet4Address from_inaddr(inaddr_type v);
131                                         ///< Construct address from integer in network byte order
132                                         /**< This call is used when interfacing with other legacy
133                                              code to convert a network byte order address in an
134                                              integer number into an INet4Address. */
135
136         ///@}
137         ///////////////////////////////////////////////////////////////////////////
138         ///\name Accessors
139         ///@{
140
141         bool local() const;             ///< \c true, if address is locally administered
142                                         /**< This call checks, if the address is within one of the
143                                              IANA private ranges. */
144         bool loopback() const;          ///< \c true, if address is within the loopback network
145                                         /**< Checks, whether the address is in the IANA loopback
146                                              network 10.0.0.0/8 */
147         bool multicast() const;         ///< \c true, if address is a multicast address
148                                         /**< Checks, whether the address is in the 224.0.0.0/4
149                                              network reserved for multicast addresses by the
150                                              IANA. */
151         bool broadcast() const;         ///< \c true, if address is 255.255.255.255
152         bool boolean_test() const;      ///< \c true, if address is non-empty (!= 0.0.0.0)
153
154         inaddr_type inaddr() const;     ///< Return the raw network byte order address
155                                         /**< This member is used to interact with legacy code.
156                                              \return */
157         address_type address() const;   ///< Return address represented as integer number
158                                         /**< This member returns the address as an integer number in
159                                              host byte order. This representation allows simple
160                                              network math operations. */
161         ////@}
162
163     private:
164         enum InAddr_t { IsInAddr };
165         INet4Address(inaddr_type addr, InAddr_t);
166         inaddr_type & iref();
167         inaddr_type iref() const;
168     };
169
170     /** \brief Output INet4Address instance as it's string representation
171         \related INet4Address
172      */
173     std::ostream & operator<<(std::ostream & os, INet4Address const & addr);
174
175     /** \brief Initialize INet4Address instance from a string representation
176         sets std::ios::failbit on the stream if an error occurred
177         \see INet4Address from_string()
178         \related INet4Address
179      */
180     std::istream & operator>>(std::istream & os, INet4Address & addr);
181
182     /** \brief CHeck INet4Address against a fixed network prefix
183
184         This helper allows to easily and efficiently check an INet4Address against an arbitrary but
185         constant network prefix. The network prefix is represented by
186
187         \par ""
188             <tt>senf::CheckINet4Network<</tt> <i>addr</i> <tt>,</tt> <i>prefix-len</i> <tt>></tt>
189
190         Where \a addr is the v4 Internet address as a 32-bit unsigned integer number in host byte
191         order and \a prefix_len is the length of the network prefix. The class exposes a single
192         static member <tt>match(</tt> <i>addr</i> <tt>)</tt> which matches the INet4Address \a addr
193         against the prefix:
194
195         \code
196         if (senf::CheckINet4Network<0x7F000000u,8u>::match(addr)) {
197             // 'addr' is within the 127.0.0.0/8 loopback network
198             ...
199         }
200         \endcode
201
202         \implementation This is implemented the way it is so the syntax is identical to the
203             CheckINet6Network syntax.
204      */
205     template <boost::uint32_t address, unsigned prefix_len>
206     class CheckINet4Network
207     {
208     public:
209         static bool match(INet4Address const & addr);
210     };
211
212     /** \brief IPv4 network prefix
213
214         This class represents an IPv4 network prefix in CIDR notation.
215       */
216     class INet4Network
217         : public boost::equality_comparable<INet4Network>,
218           public comparable_safe_bool<INet4Network>
219     {
220     public:
221         ///////////////////////////////////////////////////////////////////////////
222         ///\name Structors and default members
223         ///@{
224
225         INet4Network();                 ///< Construct empty (0.0.0.0/0) network
226         INet4Network(INet4Address const & address, unsigned prefix_len);
227                                         ///< Construct network from given address and prefix length
228         explicit INet4Network(std::string const & s); ///< Construct network from CIDR notation
229
230         ///@}
231         ///////////////////////////////////////////////////////////////////////////
232
233         INet4Address const & address() const; ///< Get the networks address
234         unsigned prefix_len() const;    ///< Get the networks prefix length
235
236         bool boolean_test() const;      ///< \c true, if INet4Network is non-empty
237         bool operator==(INet4Network const & other) const;
238                                         ///< Compare to networks for equality
239
240         bool match(INet4Address const & addr) const; ///< \c true, if the network includes \a addr
241         bool match(INet4Network const & net) const; ///< \c true, if the network includes \a net
242                                         /**< The is true, if \a net is sub-network (or the same as)
243                                              \c this. */
244
245         INet4Address host(boost::uint32_t number); ///< Return the host with the given number
246                                         /**< Returns the host with the given number within the
247                                              network. If the number is larger than the maximum
248                                              host number in the network, it is truncated. So \c
249                                              host(0) is the networks own address, \c host(1)
250                                              customarily is the default router and \c host(-1) is
251                                              the broadcast address. */
252
253         INet4Network subnet(boost::uint32_t net, unsigned prefix_len);
254                                         ///< Return the given subnet of \c this
255                                         /**< The returned INet4Network will be a subnet of \c this
256                                              with the given network number. The network number is
257                                              comprised by the bits above \a prefix_len:
258                                              \code
259                                              INet4Network("192.168.0.0/16").subnet(111u,24u) == INet4Network("192.168.111.0/24")
260                                              INet4Network("192.168.111.0/24").subnet(1u,28u) == INet4Network("192.168.111.16/28")
261                                              \endcode
262                                              \param[in] net network number
263                                              \param[in] prefix_len length of subnet prefix */
264
265     protected:
266
267     private:
268         boost::uint32_t mask() const;
269
270         unsigned prefix_len_;
271         INet4Address address_;
272     };
273
274     /** \brief Output INet4Network instance as it's string representation
275         \related INet4Network
276      */
277     std::ostream & operator<<(std::ostream & os, INet4Network const & addr);
278
279     /** \brief Initialize INet4Address instance from a string representation
280
281         sets std::ios::failbit on the stream if an error occurred
282         \see INet4Address from_string()
283         \related INet4Network
284      */
285     std::istream & operator>>(std::istream & is, INet4Network & addr);
286
287 }
288
289 ///////////////////////////////hh.e////////////////////////////////////////
290 #include "INet4Address.cci"
291 #include "INet4Address.ct"
292 #include "INet4Address.cti"
293 #endif
294
295
296 // Local Variables:
297 // mode: c++
298 // fill-column: 100
299 // comment-column: 40
300 // c-file-style: "senf"
301 // indent-tabs-mode: nil
302 // ispell-local-dictionary: "american"
303 // compile-command: "scons -u test"
304 // End: