Something went wrong. Try again.
An allocation-free Zig library for parsing, validating, formatting and classifying IPv4 and IPv6 addresses, networks, ranges and endpoints.
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! A 32-bit IPv4 address, stored as four octets in network (big-endian) order.//!//! The address is a pure network-layer address: it carries no port and no//! prefix length. See `Ipv4Network` for CIDR networks.
const std = @import("std");const json = @import("json.zig");const Writer = std.Io.Writer;
const Ipv6Address = @import("Ipv6Address.zig");const sockaddr = @import("sockaddr.zig");const Scope = @import("scope.zig").Scope;
const Ipv4Address = @This();
/// Address octets in network byte order: `octets[0]` is the most significant.octets: [4]u8,
/// Width of an IPv4 address in bits.pub const bit_count = 32;
/// The unspecified address, `0.0.0.0`.pub const unspecified: Ipv4Address = .{ .octets = .{ 0, 0, 0, 0 } };/// The loopback address, `127.0.0.1`.pub const loopback: Ipv4Address = .{ .octets = .{ 127, 0, 0, 1 } };/// The limited broadcast address, `255.255.255.255`.pub const broadcast: Ipv4Address = .{ .octets = .{ 255, 255, 255, 255 } };
pub fn init(a: u8, b: u8, c: u8, d: u8) Ipv4Address { return .{ .octets = .{ a, b, c, d } };}
/// Builds an address from its numeric value, where `0x7f000001` is `127.0.0.1`.pub fn fromInt(value: u32) Ipv4Address { var octets: [4]u8 = undefined; std.mem.writeInt(u32, &octets, value, .big); return .{ .octets = octets };}
/// The numeric value of the address, where `127.0.0.1` is `0x7f000001`.pub fn toInt(a: Ipv4Address) u32 { return std.mem.readInt(u32, &a.octets, .big);}
/// The next address, or null at the top of the address space, where there is/// no next one.////// An address is a point in a flat 32-bit space and this steps through it;/// whatever network the address happens to belong to has no bearing on which/// address follows it, so `next` will walk straight out of a network without/// noticing. A walk that should stop at a network's edge wants/// `Ipv4Network.addresses` or `Ipv4Network.hosts`, which know where to stop.pub fn next(a: Ipv4Address) ?Ipv4Address { return a.add(1);}
/// The previous address, or null at the bottom of the address space.pub fn prev(a: Ipv4Address) ?Ipv4Address { return a.sub(1);}
/// The address `delta` further up, or null when that would run off the top of/// the address space. Saturating instead of stopping is `orelse`:////// ```/// const capped = address.add(delta) orelse Ipv4Address.broadcast;/// ```pub fn add(a: Ipv4Address, delta: u32) ?Ipv4Address { const sum, const overflow = @addWithOverflow(a.toInt(), delta); return if (overflow == 1) null else .fromInt(sum);}
/// The address `delta` further down, or null when that would run off the/// bottom of the address space.pub fn sub(a: Ipv4Address, delta: u32) ?Ipv4Address { const difference, const underflow = @subWithOverflow(a.toInt(), delta); return if (underflow == 1) null else .fromInt(difference);}
pub const ParseError = error{ /// A character other than a decimal digit or `.` was found. InvalidCharacter, /// An octet was greater than 255. OctetOutOfRange, /// An octet had a redundant leading zero, as in `192.168.01.1`. Such text /// is rejected because some resolvers read a leading zero as introducing /// an octal number, making the address ambiguous. LeadingZero, /// The text held fewer than four octets. TooFewOctets, /// The text held more than four octets. TooManyOctets, /// An octet was empty, as in `192..0.1` or a trailing `.`. EmptyOctet,};
/// Parses the canonical dotted-decimal form, `a.b.c.d`.////// Parsing is strict: exactly four decimal octets are required, and the/// shorthand forms accepted by `inet_aton` (`127.1`, `0x7f.0.0.1`, octal/// octets) are all rejected.pub fn parse(text: []const u8) ParseError!Ipv4Address { var octets: [4]u8 = undefined; var count: usize = 0; var index: usize = 0; while (true) { if (count == 4) return if (index == text.len) error.EmptyOctet else error.TooManyOctets; // One pass over the octet: the value accumulates while the characters // are checked, and a bad character only wins over the checks below // because they are deferred until the whole octet has been seen. const start = index; var value: u16 = 0; var invalid = false; while (index < text.len and text[index] != '.') : (index += 1) { const digit = text[index] -% '0'; if (digit > 9) { invalid = true; } else if (index - start < 3) { value = value * 10 + digit; } } const len = index - start; if (len == 0) return error.EmptyOctet; if (invalid) return error.InvalidCharacter; if (len > 1 and text[start] == '0') return error.LeadingZero; if (len > 3 or value > 255) return error.OctetOutOfRange; octets[count] = @intCast(value); count += 1; if (index == text.len) break; index += 1; } if (count < 4) return error.TooFewOctets; return .{ .octets = octets };}
/// Whether `text` is a valid dotted-decimal address, discarding the reason/// when it is not.pub fn isValid(text: []const u8) bool { _ = parse(text) catch return false; return true;}
pub const LegacyParseError = error{ /// A character that is not a digit of the part's base, or a `0x` with /// nothing after it. InvalidCharacter, /// A part between two dots was empty, or the text was. EmptyPart, /// More than four parts. `inet_aton` reads at most four. TooManyParts, /// A part did not fit the octets left for it: at most 255 for any part /// but the last, and for the last, whatever fits the octets the earlier /// parts did not name. PartOutOfRange,};
/// Parses the text the way a C library's `inet_aton` does, accepting every/// shorthand `parse` refuses.////// This is not an alternative parser to reach for. It exists so that a/// program can find out what *somebody else* will make of a piece of text,/// and `isAmbiguous` is the question it is usually asked on behalf of.////// The forms it accepts, none of which is canonical:////// * Fewer than four parts, where the last one spreads over the octets the/// earlier ones did not name. `127.1` is `127.0.0.1`, `1.2.3` is `1.2.0.3`,/// and a bare `2130706433` is `127.0.0.1`./// * A `0` prefix meaning octal, so `010.0.0.1` is `8.0.0.1`./// * A `0x` prefix meaning hexadecimal, so `0x7f.0.0.1` is `127.0.0.1`.////// It also stops at the first whitespace character and ignores everything/// after it, which is not a shorthand but a consequence of how the C function/// decides it has finished: it requires the byte it stopped on to be a/// terminator or a space, and then never looks past it. So `1.2.3.4 x` is/// `1.2.3.4`, and `1.2 .3.4` is `1.0.0.2`. This was measured against glibc/// rather than read off the manual page, and it is the part of the behaviour/// most worth knowing about, since it turns a trailing field of any kind into/// something a C parser will silently discard.////// Leading whitespace is not accepted, by glibc or here.pub fn parseLegacy(text: []const u8) LegacyParseError!Ipv4Address { // Everything from the first space onwards is not part of the address and // is not an error either. const body = text[0 .. std.mem.findAny(u8, text, " \t\n\r\x0b\x0c") orelse text.len]; var parts: [4]u32 = undefined; var count: usize = 0; var it = std.mem.splitScalar(u8, body, '.'); while (it.next()) |part| { if (count == 4) return error.TooManyParts; parts[count] = try parseLegacyPart(part); count += 1; }
// Every part but the last names one octet; the last spreads over all the // octets left over, which is what makes `127.1` mean `127.0.0.1`. var value: u32 = 0; for (parts[0 .. count - 1], 0..) |part, i| { if (part > 255) return error.PartOutOfRange; value |= part << @intCast(8 * (3 - i)); } const tail = parts[count - 1]; const tail_bits = 8 * (5 - count); if (tail_bits < 32 and tail >= @as(u32, 1) << @intCast(tail_bits)) { return error.PartOutOfRange; } return .fromInt(value | tail);}
/// One dot-separated part, in whichever base its prefix says.fn parseLegacyPart(text: []const u8) LegacyParseError!u32 { if (text.len == 0) return error.EmptyPart; var body = text; var base: u8 = 10; if (body.len >= 2 and body[0] == '0' and (body[1] | 0x20) == 'x') { base = 16; body = body[2..]; if (body.len == 0) return error.InvalidCharacter; } else if (body.len >= 2 and body[0] == '0') { // A lone `0` stays decimal, which comes to the same thing. Anything // longer is octal, so `08` is not a number at all. base = 8; body = body[1..]; } var value: u64 = 0; for (body) |c| { const digit = std.fmt.charToDigit(c, base) catch return error.InvalidCharacter; value = value * base + digit; if (value > std.math.maxInt(u32)) return error.PartOutOfRange; } return @intCast(value);}
/// Whether this parser and a C library's `inet_aton` disagree about `text`.////// They disagree in two ways, and both matter. Either `parse` rejects text/// that `inet_aton` accepts — which is most of the shorthands — or both/// accept it and read it as different addresses.////// This is the question behind the strictness of `parse`. A program that/// checks an address against a deny list with a strict parser, and then hands/// the original text to something that resolves or connects with the system's/// own parser, has two readings of one string and a filter that can be walked/// straight past: `0x7f.0.0.1` is not loopback to the first and is loopback/// to the second. Rejecting the text is the right answer, and this says which/// text to reject loudly rather than quietly.////// `parseLegacy` is what to call to find out what the other reading actually/// is, for a log line that says so.////// There is no IPv6 counterpart. `inet_pton` has no shorthands to disagree/// about, and the IPv6 text form has been one thing since RFC 4291.pub fn isAmbiguous(text: []const u8) bool { const legacy = parseLegacy(text) catch return false; const strict = parse(text) catch return true; return !strict.eql(legacy);}
/// The longest text an IPv4 address can format to, `255.255.255.255`.pub const max_text_len = "255.255.255.255".len;
/// Writes the address in dotted-decimal form. Use the `{f}` specifier.pub fn format(a: Ipv4Address, w: *Writer) Writer.Error!void { var buffer: [max_text_len + 1]u8 = undefined; try w.writeAll(a.render(&buffer));}
/// Formats into `buffer`, returning the written slice. The buffer must be at/// least `max_text_len` bytes.pub fn bufPrint(a: Ipv4Address, buffer: []u8) error{NoSpaceLeft}![]u8 { // With a byte to spare over the longest text, `render`'s word stores fit // and the text is produced directly in the caller's buffer. if (buffer.len > max_text_len) return a.render(buffer[0 .. max_text_len + 1]); var rendered: [max_text_len + 1]u8 = undefined; const text = a.render(&rendered); if (buffer.len < text.len) return error.NoSpaceLeft; @memcpy(buffer[0..text.len], text); return buffer[0..text.len];}
/// Renders the dotted-decimal form into `buffer`, returning the written slice./// This is the one place the text is produced; `format` and `bufPrint` both/// go through it rather than through `Writer.print`, whose per-integer/// formatting costs more than the whole address.////// Each octet is built as all three digit characters plus the following dot in/// one word, with the leading zeros shifted out before the word is stored./// This is branchless where writing digit by digit would mispredict on the/// varying octet widths. The store is always four bytes, of which only the/// digits and the dot are kept; the byte past `max_text_len` absorbs the spill/// of the final octet.fn render(a: Ipv4Address, buffer: *[max_text_len + 1]u8) []u8 { var len: usize = 0; for (a.octets) |octet| { const chars: [4]u8 = .{ '0' + octet / 100, '0' + octet / 10 % 10, '0' + octet % 10, '.' }; const width: usize = 1 + @as(usize, @intFromBool(octet >= 10)) + @intFromBool(octet >= 100); // The first character sits in the low byte, so the shift drops leading // zeros and the little-endian store puts the rest back in text order. const word = std.mem.readInt(u32, &chars, .little); std.mem.writeInt(u32, buffer[len..][0..4], word >> @intCast(8 * (3 - width)), .little); len += width + 1; } return buffer[0 .. len - 1];}
/// The longest a reverse-DNS name can be, `255.255.255.255.in-addr.arpa`.pub const max_reverse_name_len = max_text_len + in_addr_arpa.len;
const in_addr_arpa = ".in-addr.arpa";
/// Writes the name this address is looked up under in the reverse DNS: the/// octets in reverse order followed by `in-addr.arpa`, as RFC 1035 §3.5/// defines it.////// 127.0.0.1 -> 1.0.0.127.in-addr.arpa////// The name carries no trailing dot. A resolver that needs an absolute name/// adds one; a name written into a zone file below `in-addr.arpa` wants the/// octets alone.pub fn reverseName(a: Ipv4Address, buffer: []u8) error{NoSpaceLeft}![]u8 { // Reversing the octets and reusing the dotted-decimal renderer is the // whole of it: a reverse name is the ordinary text form read backwards, // which is why the label order is what it is -- the DNS delegates from // the right, and an address delegates from the left. const reversed: Ipv4Address = .{ .octets = .{ a.octets[3], a.octets[2], a.octets[1], a.octets[0], } }; var rendered: [max_reverse_name_len]u8 = undefined; const text = reversed.bufPrint(&rendered) catch unreachable; rendered[text.len..][0..in_addr_arpa.len].* = in_addr_arpa.*; const len = text.len + in_addr_arpa.len; if (buffer.len < len) return error.NoSpaceLeft; @memcpy(buffer[0..len], rendered[0..len]); return buffer[0..len];}
/// Writes the reverse-DNS name to `w`, for a caller that is writing a stream/// rather than filling a buffer: the same name `reverseName` produces, with/// the buffer it needs found on the stack instead of by the caller.pub fn writeReverseName(a: Ipv4Address, w: *Writer) Writer.Error!void { var buffer: [max_reverse_name_len]u8 = undefined; // The buffer is the longest name there is, so the only error the name // could report cannot happen. try w.writeAll(a.reverseName(&buffer) catch unreachable);}
pub fn eql(a: Ipv4Address, b: Ipv4Address) bool { return std.mem.eql(u8, &a.octets, &b.octets);}
/// Orders two addresses by their numeric value.pub fn order(a: Ipv4Address, b: Ipv4Address) std.math.Order { return std.math.order(a.toInt(), b.toInt());}
/// The IPv4-mapped IPv6 address `::ffff:a.b.c.d`, as used by dual-stack/// sockets.pub fn toIpv6Mapped(a: Ipv4Address) Ipv6Address { var octets: [16]u8 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0 }; @memcpy(octets[12..], &a.octets); return .{ .octets = octets };}
/// The deprecated IPv4-compatible IPv6 address `::a.b.c.d` (RFC 4291).pub fn toIpv6Compatible(a: Ipv4Address) Ipv6Address { var octets: [16]u8 = @splat(0); @memcpy(octets[12..], &a.octets); return .{ .octets = octets };}
/// Converts to the standard library's socket address type.pub fn toStdAddress(a: Ipv4Address, port: u16) std.Io.net.Ip4Address { return .{ .bytes = a.octets, .port = port };}
/// Converts from the standard library's socket address type, dropping the port.pub fn fromStdAddress(a: std.Io.net.Ip4Address) Ipv4Address { return .{ .octets = a.bytes };}
/// What reading an address out of a socket address structure can fail on.pub const SockaddrError = sockaddr.Error;
/// Fills in a `sockaddr_in` through a pointer to one, returning the number of/// bytes written: the `socklen_t` that goes with the pointer.////// The pointer may be to a `sockaddr.in`, or to a `sockaddr` or a/// `sockaddr.storage` standing in for one, and may come from `std.posix`,/// `std.c` or `std.os.linux` alike. The whole structure is written, so every/// field of it is left with a defined value.pub fn writeSockaddr(a: Ipv4Address, port: u16, sa: anytype) u32 { return sockaddr.writeIpv4(a, port, sa);}
/// Reads an address out of a `sockaddr_in`, dropping its port.////// `error.UnexpectedAddressFamily` when the structure's `family` is not/// `AF_INET`, which is the only thing about it that can be wrong.pub fn fromSockaddr(sa: anytype) SockaddrError!Ipv4Address { return (try sockaddr.readIpv4(sa)).address;}
// Classification. The predicates below follow the IANA IPv4 Special-Purpose// Address Registry.
/// `0.0.0.0`, the unspecified ("this host") address.pub fn isUnspecified(a: Ipv4Address) bool { return a.toInt() == 0;}
/// `0.0.0.0/8`, "this network" (RFC 791).pub fn isThisNetwork(a: Ipv4Address) bool { return a.octets[0] == 0;}
/// `127.0.0.0/8`, loopback (RFC 1122).pub fn isLoopback(a: Ipv4Address) bool { return a.octets[0] == 127;}
/// `10.0.0.0/8`, `172.16.0.0/12` or `192.168.0.0/16` (RFC 1918).pub fn isPrivate(a: Ipv4Address) bool { return switch (a.octets[0]) { 10 => true, 172 => a.octets[1] & 0xf0 == 16, 192 => a.octets[1] == 168, else => false, };}
/// `100.64.0.0/10`, the shared address space used by carrier-grade NAT/// (RFC 6598).pub fn isShared(a: Ipv4Address) bool { return a.octets[0] == 100 and a.octets[1] & 0xc0 == 64;}
/// `169.254.0.0/16`, link-local (RFC 3927).pub fn isLinkLocal(a: Ipv4Address) bool { return a.octets[0] == 169 and a.octets[1] == 254;}
/// `192.0.0.0/24`, IETF protocol assignments (RFC 6890).////// Most of the block is not globally reachable, but two addresses in it are;/// this predicate answers "was this handed out for a protocol" rather than/// "is this reachable", and `isGlobal` knows the difference.pub fn isProtocolAssignment(a: Ipv4Address) bool { return a.octets[0] == 192 and a.octets[1] == 0 and a.octets[2] == 0;}
/// The two addresses inside `192.0.0.0/24` that the registry does mark/// globally reachable: `192.0.0.9`, the Port Control Protocol anycast/// address (RFC 7723), and `192.0.0.10`, the TURN anycast address/// (RFC 8155). Without this they would be hidden by the block they were/// carved out of.fn isReachableProtocolAssignment(a: Ipv4Address) bool { return a.octets[3] == 9 or a.octets[3] == 10;}
/// `192.0.2.0/24`, `198.51.100.0/24` or `203.0.113.0/24`, reserved for use in/// documentation (RFC 5737).pub fn isDocumentation(a: Ipv4Address) bool { const o = a.octets; return (o[0] == 192 and o[1] == 0 and o[2] == 2) or (o[0] == 198 and o[1] == 51 and o[2] == 100) or (o[0] == 203 and o[1] == 0 and o[2] == 113);}
/// `192.88.99.0/24`, the deprecated 6to4 relay anycast prefix (RFC 7526).pub fn is6to4Relay(a: Ipv4Address) bool { const o = a.octets; return o[0] == 192 and o[1] == 88 and o[2] == 99;}
/// `198.18.0.0/15`, reserved for benchmarking (RFC 2544).pub fn isBenchmarking(a: Ipv4Address) bool { return a.octets[0] == 198 and a.octets[1] & 0xfe == 18;}
/// `224.0.0.0/4`, multicast (RFC 5771).pub fn isMulticast(a: Ipv4Address) bool { return a.octets[0] & 0xf0 == 224;}
/// `240.0.0.0/4` minus the broadcast address, reserved for future use/// (RFC 1112).pub fn isReserved(a: Ipv4Address) bool { return a.octets[0] & 0xf0 == 240 and !a.isBroadcast();}
/// `255.255.255.255`, the limited broadcast address (RFC 919).pub fn isBroadcast(a: Ipv4Address) bool { return a.toInt() == 0xffff_ffff;}
/// Whether the address is globally reachable, meaning it is not covered by any/// entry of the IANA special-purpose registry that is marked as not globally/// reachable.////// Multicast addresses are not globally reachable in this sense; test them/// with `isMulticast` instead.pub fn isGlobal(a: Ipv4Address) bool { if (a.isProtocolAssignment()) return a.isReachableProtocolAssignment(); return !(a.isThisNetwork() or a.isPrivate() or a.isShared() or a.isLoopback() or a.isLinkLocal() or a.isDocumentation() or a.is6to4Relay() or a.isBenchmarking() or a.isMulticast() or a.isReserved() or a.isBroadcast());}
/// The single category this address falls into, which is the classification/// predicates above run in the one order that gets them all right. See/// `Scope` for what the answer means and when to prefer a predicate.pub fn scope(a: Ipv4Address) Scope { // Order matters throughout. The broadcast address sits inside the // reserved block, the documentation and benchmarking blocks sit inside no // other, and everything left over is decided by `isGlobal`. if (a.isUnspecified()) return .unspecified; if (a.isBroadcast()) return .broadcast; if (a.isLoopback()) return .loopback; if (a.isLinkLocal()) return .link_local; if (a.isPrivate()) return .private; if (a.isShared()) return .shared; if (a.isMulticast()) return .multicast; if (a.isDocumentation()) return .documentation; if (a.isBenchmarking()) return .benchmarking; if (a.isReserved()) return .reserved; if (a.isGlobal()) return .global; return .special_purpose;}
/// Writes the value as a JSON string. See `json.stringify`.pub fn jsonStringify(value: Ipv4Address, jws: anytype) !void { return json.stringify(value, jws);}
/// Reads a JSON string with `parse`. See `json.parse` for what happens to the/// reason when the text is rejected.pub fn jsonParse( allocator: std.mem.Allocator, source: anytype, options: std.json.ParseOptions,) !Ipv4Address { _ = options; return json.parse(Ipv4Address, allocator, source);}
const testing = std.testing;
test parse { try testing.expectEqual(Ipv4Address.init(192, 168, 0, 1), try parse("192.168.0.1")); try testing.expectEqual(Ipv4Address.init(0, 0, 0, 0), try parse("0.0.0.0")); try testing.expectEqual(Ipv4Address.init(255, 255, 255, 255), try parse("255.255.255.255")); try testing.expectEqual(Ipv4Address.init(10, 0, 0, 0), try parse("10.0.0.0"));}
test "parse rejects malformed text" { try testing.expectError(error.TooFewOctets, parse("1.2.3")); try testing.expectError(error.TooManyOctets, parse("1.2.3.4.5")); try testing.expectError(error.EmptyOctet, parse("1.2.3.4.")); try testing.expectError(error.EmptyOctet, parse(".1.2.3")); try testing.expectError(error.EmptyOctet, parse("1..2.3")); try testing.expectError(error.EmptyOctet, parse("")); try testing.expectError(error.OctetOutOfRange, parse("256.0.0.1")); try testing.expectError(error.OctetOutOfRange, parse("1234.0.0.1")); try testing.expectError(error.LeadingZero, parse("192.168.01.1")); try testing.expectError(error.LeadingZero, parse("00.0.0.0")); try testing.expectError(error.InvalidCharacter, parse("1.2.3.x")); try testing.expectError(error.InvalidCharacter, parse("0x7f.0.0.1")); try testing.expectError(error.InvalidCharacter, parse(" 1.2.3.4")); try testing.expectError(error.InvalidCharacter, parse("1.2.3.4 ")); try testing.expectError(error.InvalidCharacter, parse("-1.2.3.4")); // inet_aton shorthand is not accepted. try testing.expectError(error.TooFewOctets, parse("127.1"));}
test jsonStringify { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); try std.json.Stringify.value(try Ipv4Address.parse("192.0.2.1"), .{}, &w); // A JSON string holding exactly what `format` would have written. try testing.expectEqualStrings("\"192.0.2.1\"", w.buffered());}
test jsonParse { // The hook is driven directly rather than through `parseFromSlice`. // `parseFromSlice` instantiates the whole of `std.json`'s reflection // machinery once per type, and fifteen copies of it in one test binary is // more than kcov will trace -- see the note on the coverage step in // `build.zig`. Going through the scanner tests the function this test is // named after and nothing else; `root.zig` has the end-to-end one. var scanner = std.json.Scanner.initCompleteInput(testing.allocator, "\"192.0.2.1\""); defer scanner.deinit(); const value = try Ipv4Address.jsonParse(testing.allocator, &scanner, .{}); try testing.expect(value.eql(try Ipv4Address.parse("192.0.2.1")));
// As strict inside a JSON document as anywhere else, though the reason is // flattened to `InvalidCharacter` on the way out. var bad = std.json.Scanner.initCompleteInput(testing.allocator, "\"192.168.01.1\""); defer bad.deinit(); try testing.expectError( error.InvalidCharacter, Ipv4Address.jsonParse(testing.allocator, &bad, .{}), );
// Anything that is not a string is the wrong shape rather than a bad // address. var number = std.json.Scanner.initCompleteInput(testing.allocator, "42"); defer number.deinit(); try testing.expectError( error.UnexpectedToken, Ipv4Address.jsonParse(testing.allocator, &number, .{}), );}
test format { try testing.expectFmt("192.168.0.1", "{f}", .{Ipv4Address.init(192, 168, 0, 1)}); try testing.expectFmt("0.0.0.0", "{f}", .{Ipv4Address.unspecified}); try testing.expectFmt("255.255.255.255", "{f}", .{Ipv4Address.broadcast});}
test "round trip through text and integer" { const cases = [_][]const u8{ "0.0.0.0", "1.2.3.4", "127.0.0.1", "255.255.255.255" }; for (cases) |text| { const address = try parse(text); var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings(text, try address.bufPrint(&buffer)); try testing.expectEqual(address, Ipv4Address.fromInt(address.toInt())); } try testing.expectEqual(@as(u32, 0x7f000001), Ipv4Address.loopback.toInt());}
test "classification" { try testing.expect((try parse("127.0.0.1")).isLoopback()); try testing.expect((try parse("10.1.2.3")).isPrivate()); try testing.expect((try parse("172.16.0.1")).isPrivate()); try testing.expect((try parse("172.31.255.255")).isPrivate()); try testing.expect(!(try parse("172.32.0.1")).isPrivate()); try testing.expect((try parse("192.168.1.1")).isPrivate()); try testing.expect((try parse("100.64.0.1")).isShared()); try testing.expect(!(try parse("100.128.0.1")).isShared()); try testing.expect((try parse("169.254.1.1")).isLinkLocal()); try testing.expect((try parse("224.0.0.1")).isMulticast()); try testing.expect((try parse("239.255.255.255")).isMulticast()); try testing.expect((try parse("198.18.0.1")).isBenchmarking()); try testing.expect((try parse("192.0.2.1")).isDocumentation()); try testing.expect((try parse("240.0.0.1")).isReserved()); try testing.expect(!Ipv4Address.broadcast.isReserved()); try testing.expect(Ipv4Address.broadcast.isBroadcast()); try testing.expect(Ipv4Address.unspecified.isUnspecified());
try testing.expect((try parse("8.8.8.8")).isGlobal()); try testing.expect((try parse("1.1.1.1")).isGlobal()); try testing.expect(!(try parse("192.168.1.1")).isGlobal()); try testing.expect(!(try parse("127.0.0.1")).isGlobal()); try testing.expect(!(try parse("224.0.0.1")).isGlobal());}
test "conversion to IPv6" { try testing.expectFmt("::ffff:192.168.0.1", "{f}", .{Ipv4Address.init(192, 168, 0, 1).toIpv6Mapped()}); // The deprecated IPv4-compatible form is written in hex, not dotted. try testing.expectFmt("::c0a8:1", "{f}", .{Ipv4Address.init(192, 168, 0, 1).toIpv6Compatible()});}
test "ordering" { try testing.expectEqual(.lt, Ipv4Address.init(1, 2, 3, 4).order(.init(1, 2, 3, 5))); try testing.expectEqual(.eq, Ipv4Address.loopback.order(.loopback)); try testing.expectEqual(.gt, Ipv4Address.broadcast.order(.unspecified)); try testing.expect(Ipv4Address.loopback.eql(.init(127, 0, 0, 1)));}
test "reverse-DNS names" { var buffer: [max_reverse_name_len]u8 = undefined; // RFC 1035 §3.5's own example. try testing.expectEqualStrings( "52.0.2.10.in-addr.arpa", try (try parse("10.2.0.52")).reverseName(&buffer), ); try testing.expectEqualStrings( "1.0.0.127.in-addr.arpa", try loopback.reverseName(&buffer), ); // The longest one there is, which is what `max_reverse_name_len` claims. const longest = try broadcast.reverseName(&buffer); try testing.expectEqualStrings("255.255.255.255.in-addr.arpa", longest); try testing.expectEqual(max_reverse_name_len, longest.len); // A buffer that fits the name is enough; one that does not says so // rather than writing past it. var exact: [22]u8 = undefined; try testing.expectEqualStrings( "52.0.2.10.in-addr.arpa", try (try parse("10.2.0.52")).reverseName(&exact), ); var small: [21]u8 = undefined; try testing.expectError( error.NoSpaceLeft, (try parse("10.2.0.52")).reverseName(&small), );}
test "reverse-DNS names written to a writer" { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); try (try parse("10.2.0.52")).writeReverseName(&w); try testing.expectEqualStrings("52.0.2.10.in-addr.arpa", w.buffered());
// The writer form and the buffer form produce the same name, which is // the whole of what it promises. var name: [max_reverse_name_len]u8 = undefined; w = .fixed(&buffer); try broadcast.writeReverseName(&w); try testing.expectEqualStrings(try broadcast.reverseName(&name), w.buffered());
// A writer with no room left reports it rather than truncating. var full: [max_reverse_name_len - 1]u8 = undefined; var small: Writer = .fixed(&full); try testing.expectError(error.WriteFailed, broadcast.writeReverseName(&small));}
test init { const address: Ipv4Address = .init(192, 0, 2, 1); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &address.octets); try testing.expect(address.eql(try .parse("192.0.2.1")));}
test fromInt { try testing.expect(Ipv4Address.fromInt(0x7f00_0001).eql(.loopback)); try testing.expect(Ipv4Address.fromInt(0).eql(.unspecified));}
test toInt { try testing.expectEqual(@as(u32, 0x7f00_0001), Ipv4Address.loopback.toInt()); // The numeric value orders addresses the way the dotted quad reads. try testing.expect(Ipv4Address.unspecified.toInt() < Ipv4Address.broadcast.toInt());}
test parseLegacy { // Every one of these is a form `parse` refuses, and every answer here was // checked against glibc's own `inet_aton`: the two agree on 24,000 // generated strings, whitespace, bad bases and overlong numbers included. const home = Ipv4Address.loopback; try testing.expect((try parseLegacy("127.0.0.1")).eql(home)); // Fewer than four parts: the last one spreads over what is left. try testing.expect((try parseLegacy("127.1")).eql(home)); try testing.expect((try parseLegacy("2130706433")).eql(home)); try testing.expect((try parseLegacy("1.2.3")).eql(try .parse("1.2.0.3"))); // Octal and hexadecimal, which is where two readings of the same text // give two different addresses rather than the same one. try testing.expect((try parseLegacy("0177.0.0.1")).eql(home)); try testing.expect((try parseLegacy("0x7f.0.0.1")).eql(home)); try testing.expect((try parseLegacy("010.0.0.1")).eql(try .parse("8.0.0.1"))); // A lone `0` is not octal, and `08` is not a number. try testing.expect((try parseLegacy("0")).eql(Ipv4Address.unspecified)); try testing.expectError(error.InvalidCharacter, parseLegacy("08.0.0.1"));
// Parsing stops at the first whitespace and what follows is discarded, // which is the behaviour worth knowing about: a trailing field of any // kind simply vanishes. try testing.expect((try parseLegacy("1.2.3.4 x")).eql(try .parse("1.2.3.4"))); try testing.expect((try parseLegacy("1.2 .3.4")).eql(try .parse("1.0.0.2"))); // Leading whitespace is not accepted, by glibc or here. try testing.expectError(error.EmptyPart, parseLegacy(" 1.2.3.4"));
try testing.expectError(error.TooManyParts, parseLegacy("1.2.3.4.5")); try testing.expectError(error.EmptyPart, parseLegacy("1..2.3")); try testing.expectError(error.PartOutOfRange, parseLegacy("256.1.1.1")); // The last part is bounded by the octets left for it, not by 255. try testing.expect((try parseLegacy("1.65535")).eql(try .parse("1.0.255.255"))); try testing.expectError(error.PartOutOfRange, parseLegacy("1.2.65536"));}
test parseLegacyPart { // The prefix decides the base, and a lone `0` is decimal because there is // nothing after it to read as octal. try testing.expectEqual(@as(u32, 10), try parseLegacyPart("10")); try testing.expectEqual(@as(u32, 8), try parseLegacyPart("010")); try testing.expectEqual(@as(u32, 16), try parseLegacyPart("0x10")); try testing.expectEqual(@as(u32, 16), try parseLegacyPart("0X10")); try testing.expectEqual(@as(u32, 0), try parseLegacyPart("0")); try testing.expectError(error.InvalidCharacter, parseLegacyPart("0x")); try testing.expectError(error.InvalidCharacter, parseLegacyPart("09")); try testing.expectError(error.EmptyPart, parseLegacyPart("")); // The running total is checked at every digit, so an overlong number is // an error rather than a wrap. try testing.expectError(error.PartOutOfRange, parseLegacyPart("99999999999999999999"));}
test isAmbiguous { // Canonical text means the same thing to everyone. try testing.expect(!Ipv4Address.isAmbiguous("127.0.0.1")); // Text nobody can parse is not ambiguous either; it is just wrong. try testing.expect(!Ipv4Address.isAmbiguous("not an address")); try testing.expect(!Ipv4Address.isAmbiguous("256.1.1.1"));
// The forms a strict parser refuses and a C library accepts. Each of // these is loopback to `inet_aton` and nothing at all to `parse`, which // is how a deny list gets walked past. try testing.expect(Ipv4Address.isAmbiguous("127.1")); try testing.expect(Ipv4Address.isAmbiguous("0x7f.0.0.1")); try testing.expect(Ipv4Address.isAmbiguous("0177.0.0.1")); try testing.expect(Ipv4Address.isAmbiguous("2130706433")); try testing.expect(Ipv4Address.isAmbiguous("127.0.0.1 evil")); // And the octal reading, where both parsers would produce an address and // they would not be the same one. try testing.expect(Ipv4Address.isAmbiguous("010.0.0.1")); try testing.expect((try parseLegacy("010.0.0.1")).eql(try .parse("8.0.0.1")));}
test isValid { try testing.expect(isValid("192.0.2.1")); try testing.expect(!isValid("192.0.2.256")); // Whatever the parser rejects is invalid, a leading zero included. try testing.expect(!isValid("192.0.02.1"));}
test bufPrint { var buffer: [max_text_len]u8 = undefined; try testing.expectEqualStrings("192.0.2.1", try (try parse("192.0.2.1")).bufPrint(&buffer));
// Too small a buffer is the only way it fails. var small: [4]u8 = undefined; try testing.expectError(error.NoSpaceLeft, Ipv4Address.broadcast.bufPrint(&small));}
test reverseName { var buffer: [max_reverse_name_len]u8 = undefined; try testing.expectEqualStrings( "1.0.0.127.in-addr.arpa", try Ipv4Address.loopback.reverseName(&buffer), );}
test writeReverseName { var buffer: [max_reverse_name_len]u8 = undefined; var w: Writer = .fixed(&buffer); try (try parse("10.2.0.52")).writeReverseName(&w); try testing.expectEqualStrings("52.0.2.10.in-addr.arpa", w.buffered());}
test next { try testing.expect((try parse("192.0.2.1")).next().?.eql(try .parse("192.0.2.2"))); // It crosses an octet boundary, and a network boundary, without noticing // either: the space is flat. try testing.expect((try parse("192.0.2.255")).next().?.eql(try .parse("192.0.3.0"))); // Null at the top of the space. try testing.expectEqual(null, Ipv4Address.broadcast.next());}
test prev { try testing.expect((try parse("192.0.3.0")).prev().?.eql(try .parse("192.0.2.255"))); try testing.expectEqual(null, Ipv4Address.unspecified.prev());}
test add { try testing.expect((try parse("10.0.0.1")).add(255).?.eql(try .parse("10.0.1.0"))); try testing.expect((try parse("10.0.0.1")).add(0).?.eql(try .parse("10.0.0.1"))); // Null rather than wrapping round to the bottom of the space. try testing.expectEqual(null, (try parse("255.255.255.254")).add(2)); // Saturating is `orelse`. const capped = (try parse("255.255.255.254")).add(2) orelse Ipv4Address.broadcast; try testing.expect(capped.eql(Ipv4Address.broadcast));}
test sub { try testing.expect((try parse("10.0.1.0")).sub(255).?.eql(try .parse("10.0.0.1"))); try testing.expectEqual(null, (try parse("0.0.0.1")).sub(2));}
test eql { try testing.expect((try parse("192.0.2.1")).eql(.init(192, 0, 2, 1))); try testing.expect(!(try parse("192.0.2.1")).eql(.init(192, 0, 2, 2)));}
test order { try testing.expectEqual(.lt, (try parse("10.0.0.1")).order(try .parse("10.0.0.2"))); try testing.expectEqual(.eq, (try parse("10.0.0.1")).order(try .parse("10.0.0.1"))); try testing.expectEqual(.gt, (try parse("10.0.1.0")).order(try .parse("10.0.0.255")));}
test toIpv6Mapped { const mapped = (try parse("192.0.2.1")).toIpv6Mapped(); try testing.expectFmt("::ffff:192.0.2.1", "{f}", .{mapped}); try testing.expect(mapped.isIpv4Mapped());}
test toIpv6Compatible { const compatible = (try parse("192.0.2.1")).toIpv6Compatible(); try testing.expect(compatible.isIpv4Compatible()); // The low 32 bits are the address and everything above them is zero, // which is what makes the form deprecated: it is indistinguishable from a // small integer. try testing.expectEqual(@as(u128, 0xc000_0201), compatible.toInt());}
test toStdAddress { const socket = (try parse("192.0.2.1")).toStdAddress(443); try testing.expectEqualSlices(u8, &.{ 192, 0, 2, 1 }, &socket.bytes); try testing.expectEqual(@as(u16, 443), socket.port);}
test fromStdAddress { const address = fromStdAddress(.{ .bytes = .{ 192, 0, 2, 1 }, .port = 443 }); try testing.expect(address.eql(try .parse("192.0.2.1")));}
test writeSockaddr { var sa: std.posix.sockaddr.in = undefined; const len = (try parse("192.0.2.1")).writeSockaddr(443, &sa); try testing.expectEqual(@as(u32, @sizeOf(std.posix.sockaddr.in)), len); try testing.expect((try fromSockaddr(&sa)).eql(try .parse("192.0.2.1")));}
test fromSockaddr { var sa: std.posix.sockaddr.in = undefined; _ = Ipv4Address.loopback.writeSockaddr(0, &sa); try testing.expect((try fromSockaddr(&sa)).eql(.loopback));
// A structure of any other family is reported rather than misread. sa.family = std.posix.AF.INET6; try testing.expectError(error.UnexpectedAddressFamily, fromSockaddr(&sa));}
test scope { try testing.expectEqual(.private, (try parse("192.168.1.1")).scope()); try testing.expectEqual(.global, (try parse("1.1.1.1")).scope()); try testing.expectEqual(.loopback, (try parse("127.0.0.1")).scope()); try testing.expectEqual(.documentation, (try parse("192.0.2.1")).scope()); // The limited broadcast address is inside `240.0.0.0/4`, so a cascade // that asked about the reserved block first would call it reserved. try testing.expectEqual(.broadcast, Ipv4Address.broadcast.scope()); try testing.expectEqual(.reserved, (try parse("240.0.0.1")).scope()); // `0.0.0.0` is the unspecified address; the rest of `0.0.0.0/8` is not, // and has no category of its own. try testing.expectEqual(.unspecified, Ipv4Address.unspecified.scope()); try testing.expectEqual(.special_purpose, (try parse("0.1.2.3")).scope()); try testing.expectEqual(.special_purpose, (try parse("192.0.0.8")).scope()); // Except for the two anycast addresses in that block, which route. try testing.expectEqual(.global, (try parse("192.0.0.9")).scope());}
test isUnspecified { try testing.expect(Ipv4Address.unspecified.isUnspecified()); try testing.expect(!Ipv4Address.loopback.isUnspecified());}
test isThisNetwork { try testing.expect((try parse("0.1.2.3")).isThisNetwork()); try testing.expect(!(try parse("1.2.3.4")).isThisNetwork());}
test isLoopback { // The whole of 127/8, not just 127.0.0.1. try testing.expect((try parse("127.0.0.1")).isLoopback()); try testing.expect((try parse("127.255.255.254")).isLoopback()); try testing.expect(!(try parse("128.0.0.1")).isLoopback());}
test isPrivate { try testing.expect((try parse("10.1.2.3")).isPrivate()); try testing.expect((try parse("172.16.0.1")).isPrivate()); try testing.expect((try parse("192.168.1.1")).isPrivate()); // The RFC 1918 middle block is 172.16/12, which stops at 172.31. try testing.expect(!(try parse("172.32.0.1")).isPrivate());}
test isShared { try testing.expect((try parse("100.64.0.1")).isShared()); try testing.expect(!(try parse("100.128.0.1")).isShared());}
test isLinkLocal { try testing.expect((try parse("169.254.1.1")).isLinkLocal()); try testing.expect(!(try parse("169.255.1.1")).isLinkLocal());}
test isProtocolAssignment { try testing.expect((try parse("192.0.0.8")).isProtocolAssignment()); // 192.0.2/24 is the documentation block next door, not this one. try testing.expect(!(try parse("192.0.2.8")).isProtocolAssignment());}
test isReachableProtocolAssignment { try testing.expect((try parse("192.0.0.9")).isReachableProtocolAssignment()); try testing.expect((try parse("192.0.0.10")).isReachableProtocolAssignment()); // Its neighbours in the same block are not: `192.0.0.8` is the dummy // address of RFC 7600 and goes nowhere. try testing.expect(!(try parse("192.0.0.8")).isReachableProtocolAssignment());}
test isDocumentation { try testing.expect((try parse("192.0.2.1")).isDocumentation()); try testing.expect((try parse("198.51.100.1")).isDocumentation()); try testing.expect((try parse("203.0.113.1")).isDocumentation()); try testing.expect(!(try parse("192.0.3.1")).isDocumentation());}
test is6to4Relay { try testing.expect((try parse("192.88.99.1")).is6to4Relay()); try testing.expect(!(try parse("192.88.100.1")).is6to4Relay());}
test isBenchmarking { // 198.18/15, which is both 198.18 and 198.19. try testing.expect((try parse("198.18.0.1")).isBenchmarking()); try testing.expect((try parse("198.19.255.255")).isBenchmarking()); try testing.expect(!(try parse("198.20.0.1")).isBenchmarking());}
test isMulticast { try testing.expect((try parse("224.0.0.1")).isMulticast()); try testing.expect((try parse("239.255.255.255")).isMulticast()); try testing.expect(!(try parse("240.0.0.1")).isMulticast());}
test isReserved { try testing.expect((try parse("240.0.0.1")).isReserved()); // The broadcast address sits inside 240/4 but is a thing of its own. try testing.expect(!Ipv4Address.broadcast.isReserved());}
test isBroadcast { try testing.expect(Ipv4Address.broadcast.isBroadcast()); try testing.expect(!(try parse("255.255.255.254")).isBroadcast());}
test isGlobal { try testing.expect((try parse("1.1.1.1")).isGlobal()); try testing.expect(!(try parse("10.0.0.1")).isGlobal()); // Multicast is reachable but not globally reachable in the registry's // sense, so `isMulticast` is the question to ask about it. try testing.expect(!(try parse("224.0.0.1")).isGlobal()); // Most of the protocol assignment block is unreachable, but the two // anycast addresses carved out of it route. try testing.expect(!(try parse("192.0.0.8")).isGlobal()); try testing.expect((try parse("192.0.0.9")).isGlobal()); try testing.expect((try parse("192.0.0.10")).isGlobal());}
test render { // The buffer is a byte longer than the longest text, because the store // for each octet always writes four bytes and the last one spills. var buffer: [max_text_len + 1]u8 = undefined; try testing.expectEqualStrings("192.0.2.1", (try parse("192.0.2.1")).render(&buffer)); try testing.expectEqualStrings("0.0.0.0", Ipv4Address.unspecified.render(&buffer)); try testing.expectEqualStrings("255.255.255.255", Ipv4Address.broadcast.render(&buffer)); // One octet of each width, so every shift the branchless store can take is // exercised. try testing.expectEqualStrings("1.22.255.0", (try parse("1.22.255.0")).render(&buffer));}