ip2long / long2ip

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

点分十进制 IPv4 字符串与 32 位无符号整数互转(ip2long 转整数,long2ip 转回字符串)。

C C23

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

int main(void) {
    // inet_addr 返回网络字节序;ntohl 转回主机字节序
    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"); // 已是网络字节序:等价 long2ip
    printf("back: %s\n", inet_ntoa(back));

    // 经典坑:失败返回 INADDR_NONE(-1),与 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;
}
输出
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 返回网络字节序;ntohl 转回主机字节序
    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"); // 已是网络字节序:等价 long2ip
    std::cout << "back: " << inet_ntoa(back) << "\n";

    // 经典坑:失败返回 INADDR_NONE(-1),与 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;
}
输出
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 没有 ip2long:手动拼装四个字节(大端序)
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 干净地报告失败(无哨兵值)
Console.WriteLine($"not-an-ip => {(IPAddress.TryParse("not-an-ip", out _) ? "parsed" : "invalid")}");
Console.WriteLine($"max: {Ip2Long(IPAddress.Parse("255.255.255.255"))}");
输出
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() 给出 4 个 IPv4 字节;按大端序读出即 ip2long 的数值
    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 等价:用 net.IPv4(四个字节) 重组
    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 失败返回 nil
    fmt.Println("max:", binary.BigEndian.Uint32(net.ParseIP("255.255.255.255").To4()))
}
输出
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 没有 ip2long:对四个字节做移位/或运算
    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"));
    }
}
输出
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 没有 ip2long:对四个字节做移位/或运算
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);
}

// >>>(无符号右移)保证每个字节落在 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"));
输出
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"; // 往返转回点分形式
var_dump(ip2long('not-an-ip'));
var_dump(ip2long('255.255.255.255'));
输出
int(3221225985)
int(167772161)
192.0.2.1
bool(false)
int(4294967295)

Python v3.15.2

v3.15.2
import ipaddress

# ipaddress 模块对 IPv4 给出 ip2long/long2ip 语义


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"))
输出
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) 给出大端序数值:正是 ip2long
    println!("192.0.2.1 => {}", u32::from(ip));
    println!("10.0.0.1 => {}", u32::from(Ipv4Addr::new(10, 0, 0, 1)));

    // long2ip 等价: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)));
}
输出
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 没有 ip2long:对四个字节做移位/或运算;>>> 保证无符号
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"));
输出
192.0.2.1 => 3221225985
10.0.0.1 => 167772161
back: 192.0.2.1
not-an-ip => false
max: 4294967295

语言差异说明

C:POSIX inet_addr/inet_ntoa(arpa/inet.h)——注意返回值是网络字节序,要 ntohl 转主机序才是 ip2long 的数值;失败哨兵 INADDR_NONE 与 255.255.255.255 位模式相同,新代码用 inet_pton/inet_ntop 更安全。

C++:同 C(arpa/inet.h)。

C#:无内置 ip2long——IPAddress.GetAddressBytes 后手动移位拼装;解析失败用 IPAddress.TryParse 干净报告,无哨兵值。

Go:net.ParseIP + To4() + encoding/binary.BigEndian.Uint32;回转用 net.IPv4(四字节);失败返回 nil(无哨兵歧义)。

Java:无内置 ip2long——split 后移位/或运算(手写是主流做法);失败抛 IllegalArgumentException。

JavaScript:无内置——split/reduce 手写;回转用 >>> 无符号右移取字节(JS 位运算有符号 32 位坑,>>> 是惯用修正)。

PHP:ip2long/long2ip 内置互转;失败返回 false(不是异常);返回值在 64 位 PHP 上总是正数(192.0.2.1 → 3221225985),但32 位 PHP 时代曾返回负数(int 溢出),老文献的「负数 IP」源于此;典型用途是把「IP 在不在网段内」做成数值比较——字符串直接比较是错的(字典序 '9.0.0.1' > '10.0.0.1')。

Python:ipaddress.IPv4Address 与 int() 互转;失败抛 AddressValueError(异常式报告)。

Rust:Ipv4Addr 与 u32 用 From/From 互转(大端序数值),解析失败 Err;标准库自带,无依赖。

TypeScript:同 JS,手写移位 + >>>。