networking · beginner · ~15 min

Did socket() fail?

Detect the socket() error sentinel.

Challenge

The complement check: detect the socket() error sentinel, which is any negative fd.

Task

Implement int socket_failed(int fd) that returns 1 if fd < 0 (the error case), otherwise 0.

Input

One int fd — a value returned by socket().

Output

Returns 1 if fd < 0, else 0.

Example

socket_failed(-1)   ->   1
socket_failed(4)    ->   0

Input format

One integer fd returned by socket().

Output format

1 if fd < 0, else 0.

Constraints

A negative fd is the error sentinel.

Starter code

int socket_failed(int fd) {
    /* TODO */
    return 0;
}

Common mistakes

Assuming read/write transmits all requested bytes at once; ignoring socket file descriptor cleanup; unhandled endianness conversions.

Edge cases to handle

Short reads/writes; peer closing socket (recv returns 0); signal interruption (EINTR); non-blocking EAGAIN.

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.