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 | #include "shill/ip_address.h" |
| 6 | |
Chris Masone | 2aa9707 | 2011-08-09 17:35:08 -0700 | [diff] [blame^] | 7 | #include <arpa/inet.h> |
Paul Stewart | 1d18e8c | 2011-07-15 11:00:31 -0700 | [diff] [blame] | 8 | #include <netinet/in.h> |
| 9 | |
| 10 | #include <string> |
| 11 | |
| 12 | #include "shill/byte_string.h" |
| 13 | |
| 14 | namespace shill { |
| 15 | |
Chris Masone | 2aa9707 | 2011-08-09 17:35:08 -0700 | [diff] [blame^] | 16 | // static |
| 17 | const IPAddress::Family IPAddress::kAddressFamilyUnknown = AF_UNSPEC; |
| 18 | // static |
| 19 | const IPAddress::Family IPAddress::kAddressFamilyIPv4 = AF_INET; |
| 20 | // static |
| 21 | const IPAddress::Family IPAddress::kAddressFamilyIPv6 = AF_INET6; |
| 22 | |
Paul Stewart | 1d18e8c | 2011-07-15 11:00:31 -0700 | [diff] [blame] | 23 | IPAddress::IPAddress(Family family, const ByteString &address) |
| 24 | : family_(family) , |
| 25 | address_(address) {} |
| 26 | |
| 27 | IPAddress::IPAddress(Family family) |
| 28 | : family_(family) {} |
| 29 | |
| 30 | IPAddress::~IPAddress() {} |
| 31 | |
| 32 | int IPAddress::GetAddressLength(Family family) { |
| 33 | switch (family) { |
| 34 | case kAddressFamilyIPv4: |
| 35 | return sizeof(in_addr); |
| 36 | case kAddressFamilyIPv6: |
| 37 | return sizeof(in6_addr); |
| 38 | default: |
| 39 | return 0; |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | bool IPAddress::SetAddressFromString(const std::string &address_string) { |
| 44 | int address_length = GetAddressLength(family_); |
| 45 | |
| 46 | if (!address_length) { |
| 47 | return false; |
| 48 | } |
| 49 | |
| 50 | ByteString address(address_length); |
| 51 | if (inet_pton(family_, address_string.c_str(), address.GetData()) <= 0) { |
| 52 | return false; |
| 53 | } |
| 54 | address_ = address; |
| 55 | return true; |
| 56 | } |
| 57 | |
| 58 | void IPAddress::SetAddressToDefault() { |
| 59 | address_ = ByteString(GetAddressLength(family_)); |
| 60 | } |
| 61 | |
| 62 | } // namespace shill |