Include <folly/portability/SysTime.h> rather than <sys/time.h>
[folly.git] / folly / IPAddressV4.cpp
index a5db28fc50933d52375985b2ba5df1b0a69069de..ff44cee80acca2f9096e20c0cd1254f21b21fbf5 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@ using std::string;
 
 namespace folly {
 
-static IPAddressV4 loopback_addr("127.0.0.0");
 
 // free functions
 size_t hash_value(const IPAddressV4& addr) {
@@ -45,6 +44,15 @@ void toAppend(IPAddressV4 addr, fbstring* result) {
   result->append(addr.str());
 }
 
+bool IPAddressV4::validate(StringPiece ip) {
+  constexpr size_t kStrMaxLen = INET_ADDRSTRLEN;
+  std::array<char, kStrMaxLen + 1> ip_cstr;
+  const size_t len = std::min(ip.size(), kStrMaxLen);
+  std::memcpy(ip_cstr.data(), ip.data(), len);
+  ip_cstr[len] = 0;
+  struct in_addr addr;
+  return 1 == inet_pton(AF_INET, ip_cstr.data(), &addr);
+}
 
 // public static
 IPAddressV4 IPAddressV4::fromLong(uint32_t src) {
@@ -112,13 +120,22 @@ void IPAddressV4::setFromBinary(ByteRange bytes) {
 
 // public
 IPAddressV6 IPAddressV4::createIPv6() const {
-  ByteArray16 ba{{0}};
+  ByteArray16 ba{};
   ba[10] = 0xff;
   ba[11] = 0xff;
   std::memcpy(&ba[12], bytes(), 4);
   return IPAddressV6(ba);
 }
 
+// public
+IPAddressV6 IPAddressV4::getIPv6For6To4() const {
+  ByteArray16 ba{};
+  ba[0] = (uint8_t)((IPAddressV6::PREFIX_6TO4 & 0xFF00) >> 8);
+  ba[1] = (uint8_t)(IPAddressV6::PREFIX_6TO4 & 0x00FF);
+  std::memcpy(&ba[2], bytes(), 4);
+  return IPAddressV6(ba);
+}
+
 // public
 string IPAddressV4::toJson() const {
   return format(
@@ -145,10 +162,18 @@ bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet,
   return (mask == subMask);
 }
 
+// public
 bool IPAddressV4::isLoopback() const {
+  static IPAddressV4 loopback_addr("127.0.0.0");
   return inSubnetWithMask(loopback_addr, fetchMask(8));
 }
 
+// public
+bool IPAddressV4::isLinkLocal() const {
+  static IPAddressV4 linklocal_addr("169.254.0.0");
+  return inSubnetWithMask(linklocal_addr, fetchMask(16));
+}
+
 // public
 bool IPAddressV4::isNonroutable() const {
   auto ip = toLongHBO();