W3docs

Understanding PHP Network Functions

As web developers, we understand the importance of network connectivity in our applications. This is where PHP network functions come in handy. They enable us

Network connectivity is at the heart of most web applications: resolving hostnames, opening sockets, talking to other servers, and validating IP addresses. PHP ships a built‑in set of network functions that let you do all of this without external libraries. This chapter explains what those functions are, when to reach for each group, and how to use them correctly with runnable examples.

What are PHP network functions?

PHP network functions are built‑in functions that let your script communicate over a network. With them you can:

  • Resolve names — turn a hostname like www.example.com into an IP address (and back).
  • Open connections — create a TCP/UDP socket to another server and exchange raw bytes.
  • Read and write streams — send a request and read the response.
  • Work with IP addresses — convert between human‑readable strings and packed binary form, for both IPv4 and IPv6.

Because they are part of PHP's core, no pecl install or Composer package is required — the functions below are always available.

DNS and host lookup functions

Before you can connect to a server you usually need its IP address. These functions handle name resolution.

FunctionWhat it does
gethostbyname()Returns the IPv4 address for a hostname.
gethostbyaddr()Returns the hostname for an IP address (reverse lookup).
gethostbynamel()Returns a list of every IPv4 address for a hostname.
checkdnsrr()Checks whether DNS records (A, MX, etc.) exist for a host.
dns_get_record()Fetches the full DNS records for a host.

A common pairing is gethostbyname() to get an IP and checkdnsrr() to check that a host actually has DNS records — that is exactly what the practice question below asks about.

<?php

$host = "localhost";

// Resolve a hostname to its IPv4 address.
$ip = gethostbyname($host);
echo "IP for {$host}: {$ip}\n";

// Reverse lookup: IP back to a hostname.
echo "Host for {$ip}: " . gethostbyaddr($ip) . "\n";

If a name cannot be resolved, gethostbyname() returns the unchanged input string rather than throwing an error — always compare the result to the original before trusting it.

Socket connection functions

When you need a raw connection to another server, open a stream socket. The modern, recommended function is stream_socket_client(); the older fsockopen() still works but the stream API is more flexible.

FunctionUse it to
stream_socket_client()Open a client connection (recommended).
stream_socket_server()Listen for incoming connections (build a server).
pfsockopen()Open a persistent socket that survives between requests.
fsockopen()Legacy way to open a socket; prefer the stream version.

Here is a minimal HTTP request made by hand over a socket:

<?php

$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);

if (!$fp) {
    echo "Connection failed: {$errstr} ({$errno})\n";
} else {
    $request  = "GET / HTTP/1.1\r\n";
    $request .= "Host: www.example.com\r\n";
    $request .= "Connection: Close\r\n\r\n";

    fwrite($fp, $request);

    while (!feof($fp)) {
        echo fgets($fp, 128); // read the response line by line
    }
    fclose($fp);
}

This opens a TCP connection to port 80, sends a raw GET request, and prints the server's response. For real‑world HTTP work you rarely write requests by hand — see file_get_contents() for simple reads, or use cURL / Guzzle for headers, redirects, and HTTPS.

Stream I/O functions

Once a socket (or any stream) is open, these functions read and write the bytes flowing through it. They are the same functions used for file handling, because PHP treats sockets and files as streams.

  • fgets() — read one line.
  • fgetc() — read one character.
  • fread() — read a fixed number of bytes.
  • fwrite() — write data to the stream.
  • feof() — test whether the end of the stream was reached.

IP address conversion functions

These functions convert between the dotted/colon string form of an IP and its packed binary representation. They are essential when storing addresses compactly or comparing them.

FunctionDirectionFamily
inet_pton()string → packed binaryIPv4 and IPv6
inet_ntop()packed binary → stringIPv4 and IPv6
ip2long()IPv4 string → integerIPv4 only
long2ip()integer → IPv4 stringIPv4 only
<?php

$ip = "192.168.1.1";

// Pack the IPv4 string into binary, then expand it back.
$packed = inet_pton($ip);
echo "Round-trip: " . inet_ntop($packed) . "\n";

// ip2long stores an IPv4 address as a single integer (handy for databases).
$long = ip2long($ip);
echo "As integer: {$long}\n";
echo "Back to string: " . long2ip($long) . "\n";

inet_pton() / inet_ntop() work for both IPv4 and IPv6, while ip2long() / long2ip() are IPv4‑only. Prefer the inet_* pair when your code must handle IPv6.

Validating IP addresses

To check whether a string is a valid IP — for example user input — use filter_var() rather than a hand‑written regex:

<?php

$candidates = ["192.168.0.1", "999.1.1.1", "::1"];

foreach ($candidates as $value) {
    $valid = filter_var($value, FILTER_VALIDATE_IP) !== false;
    echo $value . " => " . ($valid ? "valid" : "invalid") . "\n";
}

This validates IPv4 and IPv6 in one call; add FILTER_FLAG_IPV4 or FILTER_FLAG_IPV6 to restrict the family.

When should you use these functions?

  • Low‑level protocols — building an SMTP, FTP, or custom TCP client where you control the bytes on the wire.
  • Service health checks — verifying a host resolves (checkdnsrr()) or a port is reachable (stream_socket_client() with a short timeout).
  • Storing IP data — packing addresses with inet_pton() or ip2long() to save space and enable range queries.
  • For ordinary HTTP API calls, prefer cURL or a client library; the socket functions are for when you need finer control than those provide.

Conclusion

PHP's network functions give you everything from DNS lookups to raw sockets to IP conversion, all without external dependencies. Remember the three groups: resolve a host (gethostbyname(), checkdnsrr()), connect to it (stream_socket_client()), and read/write the stream (fgets(), fwrite()). For higher‑level work, lean on cURL and Guzzle and reach for these functions only when you need lower‑level control.

Practice

Practice
Which functions are used in PHP for acquiring network IP and checking network IP, respectively?
Which functions are used in PHP for acquiring network IP and checking network IP, respectively?
Was this page helpful?