gethostbyname

gethostbyname(string $hostname): string

把主机名解析为 IPv4 地址字符串;失败时不报错,返回原样主机名。

C C23

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

static void resolve(const char *host) {
    struct addrinfo hints, *res;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET; // 仅 IPv4,与 PHP 的 gethostbyname 一致
    int err = getaddrinfo(host, NULL, &hints, &res);
    if (err != 0) {
        printf("resolve failed: %s\n", host);
        return;
    }
    char buf[INET_ADDRSTRLEN];
    struct sockaddr_in *addr = (struct sockaddr_in *)res->ai_addr;
    printf("%s\n", inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)));
    freeaddrinfo(res);
}

int main(void) {
    resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
    resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
    resolve("nonexistent.invalid");
    return 0;
}
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

C++ C++26

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

static void resolve(const char *host) {
    addrinfo hints{};
    addrinfo *res;
    hints.ai_family = AF_INET; // 仅 IPv4,与 PHP 的 gethostbyname 一致
    int err = getaddrinfo(host, NULL, &hints, &res);
    if (err != 0) {
        std::cout << "resolve failed: " << host << "\n";
        return;
    }
    char buf[INET_ADDRSTRLEN];
    auto *addr = reinterpret_cast<sockaddr_in *>(res->ai_addr);
    std::cout << inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) << "\n";
    freeaddrinfo(res);
}

int main() {
    resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
    resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
    resolve("nonexistent.invalid");
    return 0;
}
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

C# v11.0.100

v11.0.100
using System.Net;
using System.Net.Sockets;

// Dns.GetHostAddresses 可能返回多个地址;取其中的 IPv4
static void Resolve(string host)
{
    try
    {
        IPAddress[] addrs = Dns.GetHostAddresses(host);
        IPAddress? v4 = Array.Find(addrs, a => a.AddressFamily == AddressFamily.InterNetwork);
        Console.WriteLine(v4 == null ? "no IPv4 address" : v4.ToString());
    }
    catch
    {
        Console.WriteLine($"resolve failed: {host}"); // PHP 会原样返回主机名
    }
}

Resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
Resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
Resolve("nonexistent.invalid");
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "net"
)

func resolve(host string) {
    // network 参数 "ip4" = 仅 IPv4,与 PHP 的 gethostbyname 一致
    addr, err := net.ResolveIPAddr("ip4", host)
    if err != nil {
        fmt.Printf("resolve failed: %s\n", host)
        return
    }
    fmt.Println(addr.IP.String())
}

func main() {
    resolve("localhost")           // 经 /etc/hosts,不走 DNS 往返
    resolve("192.0.2.1")           // IP 字面量:原样返回,不查询
    resolve("nonexistent.invalid")
}
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

Java v27.0.1

v27.0.1
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    static void resolve(String host) {
        try {
            // getByName 对主机名与 IP 字面量一视同仁
            System.out.println(InetAddress.getByName(host).getHostAddress());
        } catch (UnknownHostException e) {
            System.out.println("resolve failed: " + host); // PHP 会原样返回主机名
        }
    }

    public static void main(String[] args) {
        resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
        resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
        resolve("nonexistent.invalid");
    }
}
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

JavaScript v26.13.1

v26.13.1
const dns = require("node:dns");

async function resolve(host) {
  try {
    // family: 4 与 PHP 仅 IPv4 的行为一致
    const { address } = await dns.promises.lookup(host, { family: 4 });
    console.log(address);
  } catch {
    console.log(`resolve failed: ${host}`); // PHP 会原样返回主机名
  }
}

(async () => {
  await resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
  await resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
  await resolve("nonexistent.invalid");
})();
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

PHP v8.6.0

v8.6.0
echo gethostbyname('localhost'), "\n"; // 经 /etc/hosts,不走 DNS 往返
echo gethostbyname('192.0.2.1'), "\n"; // IP 字面量:原样返回,不查询
echo gethostbyname('nonexistent.invalid'), "\n"; // 失败也原样返回主机名——不报错
输出
127.0.0.1
192.0.2.1
nonexistent.invalid

Python v3.15.2

v3.15.2
import socket


def resolve(host: str) -> None:
    try:
        # gethostbyname 按定义只解析 IPv4,与 PHP 的函数一致
        print(socket.gethostbyname(host))
    except OSError:
        print(f"resolve failed: {host}")  # PHP 会原样返回主机名


resolve("localhost")  # 经 /etc/hosts,不走 DNS 往返
resolve("192.0.2.1")  # IP 字面量:原样返回,不查询
resolve("nonexistent.invalid")
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

Rust v1.99.1

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

fn resolve(host: &str) {
    match (host, 0).to_socket_addrs() {
        Ok(mut addrs) => match addrs.find(|a| a.is_ipv4()) { // 只取 IPv4 结果
            Some(a) => println!("{}", a.ip()),
            None => println!("no IPv4 address"),
        },
        Err(_) => println!("resolve failed: {}", host), // PHP 会原样返回主机名
    }
}

fn main() {
    resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
    resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
    resolve("nonexistent.invalid");
}
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

TypeScript v26.13.1

v26.13.1
import { promises as dns } from "node:dns";

async function resolve(host: string): Promise<void> {
  try {
    // family: 4 与 PHP 仅 IPv4 的行为一致
    const { address } = await dns.lookup(host, { family: 4 });
    console.log(address);
  } catch {
    console.log(`resolve failed: ${host}`); // PHP 会原样返回主机名
  }
}

(async () => {
  await resolve("localhost"); // 经 /etc/hosts,不走 DNS 往返
  await resolve("192.0.2.1"); // IP 字面量:原样返回,不查询
  await resolve("nonexistent.invalid");
})();
输出
127.0.0.1
192.0.2.1
resolve failed: nonexistent.invalid

语言差异说明

C:POSIX 用 getaddrinfo(老接口 gethostbyname 已弃用);ai_family = AF_INET 限定 IPv4 与 PHP 行为对齐;失败返回错误码,需自行处理。

C++:同 C(getaddrinfo),无额外标准库封装。

C#:Dns.GetHostAddresses 可能返回多地址(IPv4+IPv6),需按 AddressFamily 过滤;失败抛异常(SocketException)。

Go:net.ResolveIPAddr("ip4", host) 用 network 参数限定 IPv4;失败返回 error;多地址场景可用 LookupHost。

Java:InetAddress.getByName 同时接受主机名与 IP 字面量;失败抛 UnknownHostException;返回多值用 getAllByName。

JavaScript:Node 的 dns.lookup 直接走系统 getaddrinfo(含 /etc/hosts),family: 4 限定 IPv4;失败 reject;dns.resolve 则纯走 DNS 不查 hosts。

PHP:gethostbyname 只做 IPv4 解析(IPv6 用 gethostbynamel 变体 dns_get_record);失败不报错而是返回原样主机名字符串——判断是否解析成功需比对返回值与输入(或改用 gethostbynamel 失败返回空数组);IP 字面量直接原样返回不走 DNS;本条目用 localhost、IP 字面量与保留 TLD .invalid(RFC 6761,保证解析失败)保证输出确定性。

Python:socket.gethostbyname 按定义只解析 IPv4;失败抛 OSError(gaierror);IPv6/多地址用 socket.getaddrinfo。

Rust:标准库 ToSocketAddrs(需配 (host, port) 元组);失败返回 Err;结果可能含 IPv4+IPv6,需 is_ipv4() 过滤。

TypeScript:同 JS,dns.lookup + family: 4。