1// Copyright (c) 2011 The Chromium 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 NET_BASE_NET_UTIL_H_ 6#define NET_BASE_NET_UTIL_H_ 7#pragma once 8 9#if defined(OS_WIN) 10#include <windows.h> 11#include <ws2tcpip.h> 12#elif defined(OS_POSIX) 13#include <sys/socket.h> 14#endif 15 16#include <list> 17#include <string> 18#include <set> 19#include <vector> 20 21#include <cstdint> 22 23namespace net { 24 25// IPAddressNumber is used to represent an IP address's numeric value as an 26// array of bytes, from most significant to least significant. This is the 27// network byte ordering. 28// 29// IPv4 addresses will have length 4, whereas IPv6 address will have length 16. 30typedef std::vector<unsigned char> IPAddressNumber; 31typedef std::vector<IPAddressNumber> IPAddressList; 32 33// Parses an IP address literal (either IPv4 or IPv6) to its numeric value. 34// Returns true on success and fills |ip_number| with the numeric value. 35bool ParseIPLiteralToNumber(const std::string& ip_literal, 36 IPAddressNumber* ip_number); 37 38// Parses an IP block specifier from CIDR notation to an 39// (IP address, prefix length) pair. Returns true on success and fills 40// |*ip_number| with the numeric value of the IP address and sets 41// |*prefix_length_in_bits| with the length of the prefix. 42// 43// CIDR notation literals can use either IPv4 or IPv6 literals. Some examples: 44// 45// 10.10.3.1/20 46// a:b:c::/46 47// ::1/128 48bool ParseCIDRBlock(const std::string& cidr_literal, 49 IPAddressNumber* ip_number, 50 size_t* prefix_length_in_bits); 51 52// Compares an IP address to see if it falls within the specified IP block. 53// Returns true if it does, false otherwise. 54// 55// The IP block is given by (|ip_prefix|, |prefix_length_in_bits|) -- any 56// IP address whose |prefix_length_in_bits| most significant bits match 57// |ip_prefix| will be matched. 58// 59// In cases when an IPv4 address is being compared to an IPv6 address prefix 60// and vice versa, the IPv4 addresses will be converted to IPv4-mapped 61// (IPv6) addresses. 62bool IPNumberMatchesPrefix(const IPAddressNumber& ip_number, 63 const IPAddressNumber& ip_prefix, 64 size_t prefix_length_in_bits); 65 66} // namespace net 67 68#endif // NET_BASE_NET_UTIL_H_ 69