Paul Stewart | 1d18e8c | 2011-07-15 11:00:31 -0700 | [diff] [blame] | 1 | // Copyright (c) 2011 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #ifndef SHILL_IP_ADDRESS_ |
| 6 | #define SHILL_IP_ADDRESS_ |
| 7 | |
| 8 | #include <arpa/inet.h> |
| 9 | |
| 10 | #include <string> |
| 11 | |
| 12 | #include "shill/byte_string.h" |
| 13 | |
| 14 | namespace shill { |
| 15 | |
| 16 | class IPAddress { |
| 17 | public: |
Paul Stewart | dd7df79 | 2011-07-15 11:09:50 -0700 | [diff] [blame] | 18 | typedef unsigned char Family; |
| 19 | static const Family kAddressFamilyUnknown = AF_UNSPEC; |
| 20 | static const Family kAddressFamilyIPv4 = AF_INET; |
| 21 | static const Family kAddressFamilyIPv6 = AF_INET6; |
Paul Stewart | 1d18e8c | 2011-07-15 11:00:31 -0700 | [diff] [blame] | 22 | |
| 23 | explicit IPAddress(Family family); |
| 24 | IPAddress(Family family, const ByteString &address); |
| 25 | ~IPAddress(); |
| 26 | |
| 27 | // Static utilities |
| 28 | // Get the length in bytes of addresses of the given family |
| 29 | static int GetAddressLength(Family family); |
| 30 | |
| 31 | // Getters and Setters |
| 32 | Family family() const { return family_; } |
| 33 | const ByteString &address() const { return address_; } |
| 34 | const unsigned char *GetConstData() const { return address_.GetConstData(); } |
| 35 | int GetLength() const { return address_.GetLength(); } |
| 36 | bool IsDefault() const { return address_.IsZero(); } |
| 37 | bool IsValid() const { |
| 38 | return family_ != kAddressFamilyUnknown && |
| 39 | GetLength() == GetAddressLength(family_); |
| 40 | } |
| 41 | |
| 42 | // Parse an IP address string |
| 43 | bool SetAddressFromString(const std::string &address_string); |
| 44 | // An uninitialized IPAddress is empty and invalid when constructed. |
| 45 | // Use SetAddressToDefault() to set it to the default or "all-zeroes" address. |
| 46 | void SetAddressToDefault(); |
| 47 | |
| 48 | bool Equals(const IPAddress &b) const { |
| 49 | return family_ == b.family_ && address_.Equals(b.address_); |
| 50 | } |
| 51 | |
Paul Stewart | 75e89d2 | 2011-08-01 10:00:02 -0700 | [diff] [blame^] | 52 | void Clone(const IPAddress &b) { |
| 53 | family_ = b.family_; |
| 54 | address_ = b.address_; |
| 55 | } |
| 56 | |
Paul Stewart | 1d18e8c | 2011-07-15 11:00:31 -0700 | [diff] [blame] | 57 | private: |
| 58 | Family family_; |
| 59 | ByteString address_; |
| 60 | DISALLOW_COPY_AND_ASSIGN(IPAddress); |
| 61 | }; |
| 62 | |
| 63 | } // namespace shill |
| 64 | |
| 65 | #endif // SHILL_IP_ADDRESS_ |