ip2long / long2ip

ip2long(string $ip): int|false — long2ip(int $ip): string

Converts a dotted-decimal IPv4 string to a 32-bit unsigned integer and back (ip2long to int, long2ip to string).

C C23

C23
#include <arpa/inet.h>
#include <stdio.h>

int main(void) {
    // inet_addr returns the value in NETWORK byte order; ntohl converts to host order
    printf("192.0.2.1 => %u\n", ntohl(inet_addr("192.0.2.1")));
    printf("10.0.0.1 => %u\n", ntohl(inet_addr("10.0.0.1")));

    struct in_addr back;
    back.s_addr = inet_addr("192.0.2.1"); // already network order: long2ip equivalent
    printf("back: %s\n", inet_ntoa(back));

    // classic pitfall: failure is INADDR_NONE (-1), the same bits as 255.255.255.255
    printf("not-an-ip => %s\n", inet_addr("not-an-ip") == INADDR_NONE ? "invalid" : "valid");
    printf("max: %u\n", ntohl(inet_addr("255.255.255.255")));
    return 0;
}
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => invalid
max: 4294967295

C++ C++26

C++26
#include <arpa/inet.h>
#include <iostream>

int main() {
    // inet_addr returns the value in NETWORK byte order; ntohl converts to host order
    std::cout << "192.0.2.1 => " << ntohl(inet_addr("192.0.2.1")) << "\n";
    std::cout << "10.0.0.1 => " << ntohl(inet_addr("10.0.0.1")) << "\n";

    in_addr back;
    back.s_addr = inet_addr("192.0.2.1"); // already network order: long2ip equivalent
    std::cout << "back: " << inet_ntoa(back) << "\n";

    // classic pitfall: failure is INADDR_NONE (-1), the same bits as 255.255.255.255
    std::cout << "not-an-ip => " << (inet_addr("not-an-ip") == INADDR_NONE ? "invalid" : "valid") << "\n";
    std::cout << "max: " << ntohl(inet_addr("255.255.255.255")) << "\n";
    return 0;
}
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => invalid
max: 4294967295

C# v11.0.100

v11.0.100
using System.Net;

// .NET has no ip2long: assemble the four octets manually (big-endian)
static uint Ip2Long(IPAddress ip)
{
    byte[] b = ip.GetAddressBytes();
    return ((uint)b[0] << 24) | ((uint)b[1] << 16) | ((uint)b[2] << 8) | b[3];
}

static string Long2Ip(uint n) => $"{n >> 24 & 255}.{n >> 16 & 255}.{n >> 8 & 255}.{n & 255}";

var ip = IPAddress.Parse("192.0.2.1");
Console.WriteLine($"192.0.2.1 => {Ip2Long(ip)}");
Console.WriteLine($"10.0.0.1 => {Ip2Long(IPAddress.Parse("10.0.0.1"))}");
Console.WriteLine($"back: {Long2Ip(Ip2Long(ip))}");
// TryParse reports failure cleanly (no sentinel value)
Console.WriteLine($"not-an-ip => {(IPAddress.TryParse("not-an-ip", out _) ? "parsed" : "invalid")}");
Console.WriteLine($"max: {Ip2Long(IPAddress.Parse("255.255.255.255"))}");
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => invalid
max: 4294967295

Go v1.27.4

v1.27.4
package main

import (
    "encoding/binary"
    "fmt"
    "net"
)

func main() {
    ip := net.ParseIP("192.0.2.1")
    // To4() yields the 4 IPv4 bytes; big-endian is the numeric value ip2long gives
    fmt.Println("192.0.2.1 =>", binary.BigEndian.Uint32(ip.To4()))
    fmt.Println("10.0.0.1 =>", binary.BigEndian.Uint32(net.ParseIP("10.0.0.1").To4()))

    // long2ip equivalent: reassemble via net.IPv4(octet1..4)
    n := uint32(3221225985)
    fmt.Println("back:", net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n)).String())

    fmt.Printf("not-an-ip => %v\n", net.ParseIP("not-an-ip") == nil) // ParseIP returns nil on failure
    fmt.Println("max:", binary.BigEndian.Uint32(net.ParseIP("255.255.255.255").To4()))
}
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => true
max: 4294967295

Java v27.0.1

v27.0.1
public class Main {
    // Java has no ip2long: shift/or over the four octets
    static long ip2long(String ip) {
        String[] parts = ip.split("\\.");
        if (parts.length != 4) {
            throw new IllegalArgumentException("bad ip: " + ip);
        }
        long n = 0;
        for (String part : parts) {
            n = (n << 8) | (Long.parseLong(part) & 0xFF);
        }
        return n;
    }

    static String long2ip(long n) {
        return (n >> 24 & 255) + "." + (n >> 16 & 255) + "." + (n >> 8 & 255) + "." + (n & 255);
    }

    public static void main(String[] args) {
        System.out.println("192.0.2.1 => " + ip2long("192.0.2.1"));
        System.out.println("10.0.0.1 => " + ip2long("10.0.0.1"));
        System.out.println("back: " + long2ip(ip2long("192.0.2.1")));
        try {
            ip2long("not-an-ip");
            System.out.println("not-an-ip => parsed");
        } catch (IllegalArgumentException e) {
            System.out.println("not-an-ip => invalid");
        }
        System.out.println("max: " + ip2long("255.255.255.255"));
    }
}
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => invalid
max: 4294967295

JavaScript v26.13.1

v26.13.1
// JS has no ip2long: shift/or over the four octets
function ip2long(ip) {
  const parts = ip.split(".");
  if (parts.length !== 4 || parts.some((p) => !/^\d+$/.test(p))) return false;
  return parts.reduce((acc, p) => acc * 256 + Number(p), 0);
}

// >>> (unsigned right shift) keeps every octet in 0..255
function long2ip(n) {
  return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join(".");
}

console.log("192.0.2.1 =>", ip2long("192.0.2.1"));
console.log("10.0.0.1 =>", ip2long("10.0.0.1"));
console.log("back:", long2ip(ip2long("192.0.2.1")));
console.log("not-an-ip =>", ip2long("not-an-ip"));
console.log("max:", ip2long("255.255.255.255"));
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => false
max: 4294967295

PHP v8.6.0

v8.6.0
var_dump(ip2long('192.0.2.1'), ip2long('10.0.0.1'));
echo long2ip(ip2long('192.0.2.1')), "\n"; // round trip back to the dotted form
var_dump(ip2long('not-an-ip'));
var_dump(ip2long('255.255.255.255'));
Output
int(3221225985)
int(167772161)
192.0.2.1
bool(false)
int(4294967295)

Python v3.15.2

v3.15.2
import ipaddress

# the ipaddress module gives ip2long/long2ip semantics for IPv4
def ip2long(ip: str) -> int:
    return int(ipaddress.IPv4Address(ip))


def long2ip(n: int) -> str:
    return str(ipaddress.IPv4Address(n))


print("192.0.2.1 =>", ip2long("192.0.2.1"))
print("10.0.0.1 =>", ip2long("10.0.0.1"))
print("back:", long2ip(ip2long("192.0.2.1")))
try:
    ip2long("not-an-ip")
except ipaddress.AddressValueError:
    print("not-an-ip => invalid")
print("max:", ip2long("255.255.255.255"))
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => invalid
max: 4294967295

Rust v1.99.1

v1.99.1
use std::net::Ipv4Addr;

fn main() {
    let ip: Ipv4Addr = "192.0.2.1".parse().unwrap();
    // u32::from(Ipv4Addr) is the big-endian numeric value: exactly ip2long
    println!("192.0.2.1 => {}", u32::from(ip));
    println!("10.0.0.1 => {}", u32::from(Ipv4Addr::new(10, 0, 0, 1)));

    // long2ip equivalent: Ipv4Addr::from(u32)
    println!("back: {}", Ipv4Addr::from(3221225985u32));

    println!("not-an-ip => {}", "not-an-ip".parse::<Ipv4Addr>().is_err());
    println!("max: {}", u32::from(Ipv4Addr::new(255, 255, 255, 255)));
}
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => true
max: 4294967295

TypeScript v26.13.1

v26.13.1
// TS has no ip2long: shift/or over the four octets; >>> keeps it unsigned
function ip2long(ip: string): number | false {
  const parts = ip.split(".");
  if (parts.length !== 4 || parts.some((p) => !/^\d+$/.test(p))) return false;
  return parts.reduce((acc, p) => acc * 256 + Number(p), 0);
}

function long2ip(n: number): string {
  return [n >>> 24, (n >>> 16) & 255, (n >>> 8) & 255, n & 255].join(".");
}

console.log("192.0.2.1 =>", ip2long("192.0.2.1"));
console.log("10.0.0.1 =>", ip2long("10.0.0.1"));
console.log("back:", long2ip(ip2long("192.0.2.1") as number));
console.log("not-an-ip =>", ip2long("not-an-ip"));
console.log("max:", ip2long("255.255.255.255"));
Output
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => false
max: 4294967295

Language differences

C: POSIX inet_addr/inet_ntoa (arpa/inet.h) — the return value is in network byte order; apply ntohl to get the ip2long numeric value; the failure sentinel INADDR_NONE shares its bit pattern with 255.255.255.255, so modern code prefers inet_pton/inet_ntop.

C++: same as C (arpa/inet.h).

C#: no built-in ip2long — shift/or over IPAddress.GetAddressBytes; parse failures report cleanly via IPAddress.TryParse, no sentinel values.

Go: net.ParseIP + To4() + encoding/binary.BigEndian.Uint32; reverse with net.IPv4(octets); failure returns nil (no sentinel ambiguity).

Java: no built-in ip2long — split then shift/or (hand-writing is the mainstream approach); failure throws IllegalArgumentException.

JavaScript: no built-in — split/reduce by hand; the reverse uses >>> unsigned right shift to extract octets (JS bitwise ops are signed 32-bit, >>> is the idiomatic fix).

PHP: ip2long/long2ip built in; failure returns false (not an exception); on 64-bit PHP the value is always positive (192.0.2.1 → 3221225985), but 32-bit PHP once returned negatives (int overflow) — old literature's "negative IPs" come from that; the typical use is numeric range checks for "is this IP in a subnet" — comparing strings directly is wrong (lexicographic '9.0.0.1' > '10.0.0.1').

Python: ipaddress.IPv4Address converts with int(); failure raises AddressValueError (exception-style reporting).

Rust: Ipv4Addr ↔ u32 via From (big-endian numeric value); parsing failures return Err; standard library only, no dependencies.

TypeScript: same as JS — hand-written shifts with >>>.