Introducing swift-ip: a portable library for working with IP addresses

hi all, i’m pleased to announce the initial public release of the swift-ip library — a portable, Foundation-free library for working with IP addresses.

Why use swift-ip?

The IP address types defined by the Network framework are Darwin-only, which precludes their use in server-side code.

The swift-nio library provides a multi-platform SocketAddress type, but it is heap-allocated and reference-counted, and requires linking against the entire NIOCore module. This makes it unsuitable as a high-performance currency type for purposes such as firewall implementations or metrics collection.

Who is using swift-ip?

The Swiftinit documentation index currently uses the swift-ip library to verify clients (such as Googlebot and GitHub Webhooks) and combat abuse.

Requirements

The swift-ip library requires Swift 6.0 or later. This is because IP.V6 uses UInt128.

Platform Status
:penguin: Linux Tests
:green_apple: Darwin Tests
:green_apple: Darwin (iOS) iOS
:green_apple: Darwin (tvOS) tvOS
:green_apple: Darwin (visionOS) visionOS
:green_apple: Darwin (watchOS) watchOS

Check deployment minimums

18 Likes

Would it make sense for IP to be more than just a namespace and instead have two cases v4(V4) and v6(V6)?

i tried that while the library was still internal, but it just didn’t end up being very useful. for example, == isn’t very well-defined because an IPv4 address can also be mapped to an IPv6 address, and you end up having to decide if 1.2.3.4 == ::ffff:1.2.3.4 or not.

having the two case layout is also not great from a padding perspective — IP.V6 has 16 byte alignment, so adding the v4 case effectively doubles its memory footprint.

the best way to handle both IPv4 and IPv6 at the same time is to just map everything to IPv6.

1 Like