blob: 16e07bbcfe2a9096585d4dbee0567e2bd83ab002 [file] [log] [blame]
Paul Stewart1d18e8c2011-07-15 11:00:31 -07001// 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 Masone2aa97072011-08-09 17:35:08 -07007#include <arpa/inet.h>
Paul Stewart1d18e8c2011-07-15 11:00:31 -07008#include <netinet/in.h>
9
10#include <string>
11
12#include "shill/byte_string.h"
13
14namespace shill {
15
Chris Masone2aa97072011-08-09 17:35:08 -070016// static
17const IPAddress::Family IPAddress::kAddressFamilyUnknown = AF_UNSPEC;
18// static
19const IPAddress::Family IPAddress::kAddressFamilyIPv4 = AF_INET;
20// static
21const IPAddress::Family IPAddress::kAddressFamilyIPv6 = AF_INET6;
22
Paul Stewart1d18e8c2011-07-15 11:00:31 -070023IPAddress::IPAddress(Family family, const ByteString &address)
24 : family_(family) ,
25 address_(address) {}
26
27IPAddress::IPAddress(Family family)
28 : family_(family) {}
29
30IPAddress::~IPAddress() {}
31
32int 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
43bool 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
58void IPAddress::SetAddressToDefault() {
59 address_ = ByteString(GetAddressLength(family_));
60}
61
62} // namespace shill