gethostbyname
gethostbyname(string $hostname): string
Resolves a hostname to its IPv4 address string; on failure it raises no error and returns the hostname unchanged.
C 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 only, like PHP's 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"); // via /etc/hosts, no DNS round trip
resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid");
return 0;
}
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
C++ C++26
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netdb.h>
static void resolve(const char *host) {
addrinfo hints{}, *res;
hints.ai_family = AF_INET; // IPv4 only, like PHP's 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"); // via /etc/hosts, no DNS round trip
resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid");
return 0;
}
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
C# v11.0.100
using System.Net;
using System.Net.Sockets;
// Dns.GetHostAddresses may return several addresses; pick the IPv4 one
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 returns the name instead
}
}
Resolve("localhost"); // via /etc/hosts, no DNS round trip
Resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
Resolve("nonexistent.invalid");
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
Go v1.27.4
package main
import (
"fmt"
"net"
)
func resolve(host string) {
// network "ip4" = IPv4 only, like PHP's 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") // via /etc/hosts, no DNS round trip
resolve("192.0.2.1") // IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid")
}
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
Java v27.0.1
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
static void resolve(String host) {
try {
// getByName accepts hostnames and IP literals alike
System.out.println(InetAddress.getByName(host).getHostAddress());
} catch (UnknownHostException e) {
System.out.println("resolve failed: " + host); // PHP returns the name instead
}
}
public static void main(String[] args) {
resolve("localhost"); // via /etc/hosts, no DNS round trip
resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid");
}
}
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
JavaScript v26.13.1
const dns = require("node:dns");
async function resolve(host) {
try {
// family: 4 matches PHP's IPv4-only behaviour
const { address } = await dns.promises.lookup(host, { family: 4 });
console.log(address);
} catch {
console.log(`resolve failed: ${host}`); // PHP returns the name instead
}
}
(async () => {
await resolve("localhost"); // via /etc/hosts, no DNS round trip
await resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
await resolve("nonexistent.invalid");
})();
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
PHP v8.6.0
echo gethostbyname('localhost'), "\n"; // via /etc/hosts, no DNS round trip
echo gethostbyname('192.0.2.1'), "\n"; // IP literal: returned unchanged, no lookup
echo gethostbyname('nonexistent.invalid'), "\n"; // failure also returns the name — no error
127.0.0.1 192.0.2.1 nonexistent.invalid
Python v3.15.2
import socket
def resolve(host: str) -> None:
try:
# gethostbyname is IPv4-only by definition, like PHP's function
print(socket.gethostbyname(host))
except OSError:
print(f"resolve failed: {host}") # PHP returns the name instead
resolve("localhost") # via /etc/hosts, no DNS round trip
resolve("192.0.2.1") # IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid")
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
Rust 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()) { // keep the IPv4 result
Some(a) => println!("{}", a.ip()),
None => println!("no IPv4 address"),
},
Err(_) => println!("resolve failed: {}", host), // PHP returns the name instead
}
}
fn main() {
resolve("localhost"); // via /etc/hosts, no DNS round trip
resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
resolve("nonexistent.invalid");
}
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
TypeScript v26.13.1
import { promises as dns } from "node:dns";
async function resolve(host: string): Promise<void> {
try {
// family: 4 matches PHP's IPv4-only behaviour
const { address } = await dns.lookup(host, { family: 4 });
console.log(address);
} catch {
console.log(`resolve failed: ${host}`); // PHP returns the name instead
}
}
(async () => {
await resolve("localhost"); // via /etc/hosts, no DNS round trip
await resolve("192.0.2.1"); // IP literal: returned unchanged, no lookup
await resolve("nonexistent.invalid");
})();
127.0.0.1 192.0.2.1 resolve failed: nonexistent.invalid
Language differences
C: POSIX uses getaddrinfo (the old gethostbyname is deprecated); ai_family = AF_INET restricts to IPv4, matching PHP's behaviour; failures return an error code you must handle.
C++: same as C (getaddrinfo), no extra standard-library wrapper.
C#: Dns.GetHostAddresses may return several addresses (IPv4+IPv6), filter by AddressFamily; failure throws (SocketException).
Go: net.ResolveIPAddr("ip4", host) restricts to IPv4 via the network parameter; failures return an error; for multiple addresses use LookupHost.
Java: InetAddress.getByName accepts hostnames and IP literals alike; failure throws UnknownHostException; use getAllByName for multiple results.
JavaScript: Node's dns.lookup goes through the system getaddrinfo (including /etc/hosts); family: 4 restricts to IPv4; failures reject; dns.resolve is pure DNS and skips hosts.
PHP: gethostbyname resolves IPv4 only (for IPv6 see dns_get_record variants); on failure it returns the hostname string unchanged instead of erroring — to detect success, compare the result with the input (or use gethostbynamel, which returns an empty array on failure); IP literals return unchanged without a DNS lookup; this entry uses localhost, an IP literal, and the reserved TLD .invalid (RFC 6761, guaranteed to fail) for deterministic output.
Python: socket.gethostbyname resolves IPv4 only by definition; failure raises OSError (gaierror); for IPv6/multiple addresses use socket.getaddrinfo.
Rust: the standard library's ToSocketAddrs (needs a (host, port) tuple); failures return Err; results may mix IPv4+IPv6, so filter with is_ipv4().
TypeScript: same as JS — dns.lookup with family: 4.