networking · beginner · ~15 min

Valid socket fd?

Check the socket() result.

Challenge

socket() returns a non-negative file descriptor on success, or -1 on error. Check whether a returned fd indicates success.

Task

Implement int socket_ok(int fd) that returns 1 if fd >= 0 (success), otherwise 0.

Input

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

Output

Returns 1 if fd >= 0, else 0.

Example

socket_ok(3)    ->   1
socket_ok(0)    ->   1
socket_ok(-1)   ->   0

Edge cases

  • fd == 0 is a valid descriptor; only -1 (negative) is the error sentinel.

Input format

One integer fd returned by socket().

Output format

1 if fd >= 0, else 0.

Constraints

Only a negative fd indicates failure; 0 is valid.

Starter code

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

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