fsockopen

fsockopen(string $hostname, int $port = -1, int &$error_code = null, string &$error_message = null, ?float $timeout = null): resource|false

Low-level TCP/Unix socket client: returns a stream resource on success (fwrite/fgets/fclose apply) or false with errno/errstr filled on failure.

C C23

C23
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    // the low-level equivalent of fsockopen(): socket(2) + connect(2) in full
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9); // discard: almost surely closed on localhost
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
    printf("%d\n", rc == -1); // refused: connect fails — fsockopen() returns false
    printf("%d\n", fd >= 0);  // the socket itself opened fine
    close(fd);
    return 0;
}
Output
1
1

C++ C++26

C++26
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

int main() {
    // POSIX sockets in C++: socket() + connect(), exactly like the C example
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    sockaddr_in addr{};
    addr.sin_family = AF_INET;
    addr.sin_port = htons(9); // discard: almost surely closed on localhost
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    bool ok = connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0;
    std::cout << std::boolalpha << !ok << "\n"; // refused: fsockopen() returns false
    close(fd);
    return 0;
}
Output
true

C# v11.0.100

v11.0.100
using System.Net.Sockets;

try {
    using var client = new TcpClient("127.0.0.1", 9); // discard: almost surely closed
    Console.WriteLine(false);
} catch (SocketException) {
    Console.WriteLine(true); // connection refused — fsockopen() returning false
}
Output
True

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net"
	"time"
)

func main() {
	conn, err := net.DialTimeout("tcp", "127.0.0.1:9", 2*time.Second) // discard port
	fmt.Println(err != nil) // connection refused
	if conn != nil {
		conn.Close()
	}
}
Output
true

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

public class Main {
    public static void main(String[] args) throws IOException {
        try {
            new Socket("127.0.0.1", 9); // discard: almost surely closed
            System.out.println(false);
        } catch (ConnectException e) {
            System.out.println(true); // connection refused — fsockopen() returning false
        }
    }
}
Output
true

JavaScript v26.13.1

v26.13.1
const net = require("node:net");
// a refused localhost connect is deterministic and needs no external network
const s = net.connect(9, "127.0.0.1"); // discard: almost surely closed
s.on("connect", () => { console.log(false); s.end(); });
s.on("error", () => console.log(true)); // ECONNREFUSED — fsockopen() returning false
Output
true

PHP v8.6.0

v8.6.0
$fp = @fsockopen('127.0.0.1', 9, $errno, $errstr, 2); // discard: almost surely closed
var_dump($fp === false); // refused: false, with errno/errstr filled (platform-specific, not printed)
// success path (see notes): $fp is a stream — fwrite()/fgets()/fclose() apply
Output
bool(true)

Python v3.15.2

v3.15.2
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect(("127.0.0.1", 9))  # discard: almost surely closed
    print(False)
except OSError:
    print(True)  # connection refused — fsockopen() returning false
finally:
    s.close()
Output
True

Rust v1.99.1

v1.99.1
// a refused localhost connect is deterministic; no external network involved
fn main() {
    let result = std::net::TcpStream::connect("127.0.0.1:9"); // discard port
    println!("{}", result.is_err()); // Err: connection refused
}
Output
true

TypeScript v26.13.1

v26.13.1
import * as net from "node:net";
// a refused localhost connect is deterministic and needs no external network
const s: net.Socket = net.connect(9, "127.0.0.1"); // discard: almost surely closed
s.on("connect", () => { console.log(false); s.end(); });
s.on("error", () => console.log(true)); // ECONNREFUSED — fsockopen() returning false
Output
true

Language differences

Deterministic strategy: the example connects to 127.0.0.1 port 9 (the nearly-always-closed discard port) — the failure boolean is a derived fact that needs no external network; errno/errstr text varies by platform (refused: macOS 61 / Linux 111) and is NOT printed.

Success path (described in notes, not demoed in code): $fp is a stream resource — fwrite()/fgets()/fclose() apply directly, enough for a minimal hand-written HTTP client; the modern alternative is stream_socket_client() (manual See Also).

PHP: fsockopen blocks by default and its timeout parameter covers only the connect phase (use stream_set_timeout() for read/write); UDP is connectionless — failures surface only when you read or write (manual Warning).

C: full socket(2) + connect(2) expansion; a refused connect returns -1; relies on the POSIX header family (sys/socket, netinet/in, arpa/inet, unistd).

Go net.DialTimeout, Java Socket (refused throws ConnectException), C# TcpClient, Python socket.connect (refused raises OSError), Rust TcpStream::connect (returns Err) — five different shapes, equivalent failure semantics.

JS/TS: Node net.connect is asynchronous — the example prints the derived fact inside the callback.

If port 9 happens to be occupied, any closed high port works; a localhost refusal returns instantly on every platform, so the 2-second timeout in the example is only a safety net.