Skip to content

Instantly share code, notes, and snippets.

@qpwo
Created March 29, 2025 20:31
Show Gist options
  • Save qpwo/9f577f1ca74f7176687f9e6130bab535 to your computer and use it in GitHub Desktop.
Save qpwo/9f577f1ca74f7176687f9e6130bab535 to your computer and use it in GitHub Desktop.
top 250 c standard library things
  • <stdio.h> (Standard Buffered Input/Output)

    • Provides core functions for performing input and output operations, primarily using buffered streams (FILE*) for efficiency, including standard streams (stdin, stdout, stderr), file operations, and formatted I/O.
    • FILE: Type representing a buffered file stream structure.
    • stdin: (FILE *) Macro representing the standard input stream.
    • stdout: (FILE *) Macro representing the standard output stream.
    • stderr: (FILE *) Macro representing the standard error stream.
    • EOF: (int) Macro representing End-Of-File (typically -1).
    • NULL: Macro representing a null pointer constant (often (void*)0). Also defined in other headers like <stdlib.h> and <stddef.h>.
    • size_t: Unsigned integer type for object sizes, counts. Also defined in <stddef.h>, <stdlib.h>, <string.h>.
    • int printf(const char *format, ...): Print formatted string output to stdout. Returns number of characters written or negative on error.
    • int fprintf(FILE *stream, const char *format, ...): Print formatted string output to the specified stream. Returns number of characters written or negative on error.
    • int snprintf(char *str, size_t size, const char *format, ...): Print formatted output to the character string str, writing at most size bytes (including null terminator). Safer alternative to sprintf. Returns number of characters that would have been written (excluding null) if size was large enough, or negative on error.
    • int sprintf(char *str, const char *format, ...): UNSAFE! Print formatted output to the character string str. No bounds checking! Can easily cause buffer overflows. Returns number of characters written (excluding null).
    • int scanf(const char *format, ...): Read formatted input from stdin. Returns number of items successfully assigned or EOF.
    • int fscanf(FILE *stream, const char *format, ...): Read formatted input from the specified stream. Returns number of items successfully assigned or EOF.
    • int sscanf(const char *str, const char *format, ...): Read formatted input from the character string str. Returns number of items successfully assigned or EOF.
    • FILE *fopen(const char *pathname, const char *mode): Open the file specified by pathname with the given mode (e.g., "r", "w", "a", "rb", "wb", "ab", "+ variants"). Returns FILE * stream or NULL on error (check errno).
    • int fclose(FILE *stream): Close the specified file stream, flushing any buffered data. Returns 0 on success, EOF on error.
    • size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream): Read nmemb items, each size bytes long, from stream into the buffer ptr. Used for binary input. Returns number of items successfully read (may be less than nmemb at EOF or error).
    • size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream): Write nmemb items, each size bytes long, from buffer ptr to stream. Used for binary output. Returns number of items successfully written (may be less than nmemb on error).
    • char *fgets(char *s, int size, FILE *stream): Read at most size-1 characters from stream into the buffer s. Stops on newline (which is included) or EOF. Null-terminates s. Safer than gets. Returns s on success, NULL on EOF/error.
    • int fputs(const char *s, FILE *stream): Write the null-terminated string s to stream. Does not write the null terminator or add a newline. Returns non-negative on success, EOF on error.
    • int puts(const char *s): Write the null-terminated string s and a trailing newline to stdout. Returns non-negative on success, EOF on error.
    • int fgetc(FILE *stream): Read the next character from stream as an unsigned char cast to an int. Returns the character or EOF on end-of-file or error.
    • int getc(FILE *stream): Similar to fgetc, potentially implemented as a macro (beware side effects in arguments).
    • int getchar(void): Equivalent to getc(stdin). Read next char from standard input.
    • int fputc(int c, FILE *stream): Write the character c (cast to unsigned char) to stream. Returns the character written or EOF on error.
    • int putc(int c, FILE *stream): Similar to fputc, potentially implemented as a macro.
    • int putchar(int c): Equivalent to putc(c, stdout). Write char c to standard output.
    • int fflush(FILE *stream): Flush the output buffer of the stream. If stream is NULL, flush all output streams. Returns 0 on success, EOF on error.
    • int fseek(FILE *stream, long offset, int whence): Set the file position indicator for stream. whence is SEEK_SET (start), SEEK_CUR (current), SEEK_END (end). Returns 0 on success, non-zero on error.
    • long ftell(FILE *stream): Return the current value of the file position indicator for stream, or -1L on error.
    • void rewind(FILE *stream): Equivalent to fseek(stream, 0L, SEEK_SET); clearerr(stream). Resets position to start and clears error/EOF flags.
    • int feof(FILE *stream): Check if the end-of-file indicator for stream is set. Returns non-zero if EOF, 0 otherwise.
    • int ferror(FILE *stream): Check if the error indicator for stream is set. Returns non-zero if error, 0 otherwise.
    • void clearerr(FILE *stream): Clear the end-of-file and error indicators for stream.
    • void perror(const char *s): Print the string s, a colon, a space, and the system error message corresponding to the current errno value to stderr.
    • int remove(const char *pathname): Delete the file specified by pathname. Returns 0 on success, non-zero on error.
    • int rename(const char *oldpath, const char *newpath): Rename/move the file oldpath to newpath. Returns 0 on success, non-zero on error.
    • char *gets(char *s): UNSAFE! EXTREMELY DANGEROUS! Reads a line from stdin into s without any bounds checking. Never use this function. Removed in C11.
    • int setvbuf(FILE *stream, char *buf, int mode, size_t size): Set the buffering mode (_IOFBF, _IOLBF, _IONBF) and optionally buffer (buf, size) for stream. Must be called after opening but before I/O. Returns 0 on success.
    • char *tmpnam(char *s): UNSAFE! Generates a unique temporary filename. Prone to race conditions between generation and file creation. Use mkstemp instead.
    • FILE *tmpfile(void): Creates and opens a unique temporary binary file ("wb+") that is automatically removed when closed or program terminates. Returns FILE* or NULL. Safer than tmpnam.
  • <stdlib.h> (Standard Library Utilities)

    • Provides functions for memory allocation, process control, string conversions, pseudo-random number generation, searching, sorting, and other general utilities.
    • size_t: Unsigned integer type for object sizes, counts. Also defined in <stddef.h>, <stdio.h>, <string.h>.
    • NULL: Macro representing a null pointer constant. Also defined elsewhere.
    • void *malloc(size_t size): Allocate size bytes of raw, uninitialized memory block dynamically on the heap; returns pointer to allocated memory or NULL on failure.
    • void free(void *ptr): Deallocate the memory block pointed to by ptr (which must have been returned by malloc, calloc, or realloc, or be NULL). Passing NULL is safe and does nothing.
    • void *calloc(size_t nmemb, size_t size): Allocate memory for an array of nmemb elements of size bytes each, initialize allocated memory to zero; returns pointer or NULL on failure.
    • void *realloc(void *ptr, size_t size): Change the size of the previously allocated memory block at ptr to size bytes. May move the block. Returns new pointer or NULL on failure. If ptr is NULL, equivalent to malloc(size). If size is 0, may free ptr or return unique pointer (behavior varies, best to use free explicitly).
    • void exit(int status): Terminate the calling process normally. Performs cleanup (flushes stdio, calls atexit handlers) then calls _exit(status). status is exit code (0 or EXIT_SUCCESS for success, EXIT_FAILURE or non-zero for failure).
    • void abort(void): Cause abnormal process termination (often by raising SIGABRT). May not perform standard cleanup.
    • int atexit(void (*func)(void)): Register a function func to be called automatically at normal program termination (exit() or return from main). Returns 0 on success.
    • long strtol(const char *nptr, char **endptr, int base): Convert the initial part of the string nptr to a long int value according to the given base (0, 2-36). Stores pointer to first invalid char in *endptr (if not NULL). Robust error checking via errno and endptr.
    • unsigned long strtoul(const char *nptr, char **endptr, int base): Convert the initial part of the string nptr to an unsigned long int. Similar robustness to strtol.
    • double strtod(const char *nptr, char **endptr): Convert the initial part of the string nptr to a double. Similar robustness. Robust error checking via errno and endptr.
    • int rand(void): Return a pseudo-random integer between 0 and RAND_MAX. Low quality PRNG, not suitable for cryptography or serious simulations.
    • void srand(unsigned int seed): Seed the pseudo-random number generator used by rand() with seed. Often seeded with time(NULL).
    • void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Sort an array base of nmemb elements each of size bytes, using the compar function for comparison. compar(a, b) should return <0 if a<b, 0 if a==b, >0 if a>b.
    • void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Perform binary search for key in the sorted array base. Returns pointer to matching element or NULL if not found. compar function same as for qsort.
    • char *getenv(const char *name): Get the value of an environment variable name. Returns pointer to value string (do not modify) or NULL if not found.
    • int system(const char *command): Execute a shell command. Returns command's exit status or -1 on error. Warning: Security risks if command string contains untrusted user input (potential command injection). If command is NULL, returns non-zero if shell is available, 0 otherwise.
    • int abs(int j): Compute absolute value of integer j. (Behavior undefined for INT_MIN).
    • long labs(long j): Compute absolute value of long integer j. (Behavior undefined for LONG_MIN).
    • div_t div(int numerator, int denominator): Compute integer division numerator / denominator. Returns div_t struct containing quot (quotient) and rem (remainder). Handles signs correctly.
    • ldiv_t ldiv(long numerator, long denominator): Long integer version of div. Returns ldiv_t struct.
    • int atoi(const char *nptr): UNSAFE (limited)! Convert initial part of string nptr to int. No error checking (returns 0 on error, indistinguishable from valid 0). Use strtol for robustness.
    • long atol(const char *nptr): UNSAFE (limited)! Convert initial part of string nptr to long. No error checking. Use strtol.
    • double atof(const char *nptr): UNSAFE (limited)! Convert initial part of string nptr to double. Limited error checking. Use strtod for robustness.
    • char *mktemp(char *template): UNSAFE! Creates a unique temporary filename based on template (which must end in XXXXXX). Modifies template. Prone to race conditions. Use mkstemp. Removed in POSIX.1-2008.
    • int mkstemp(char *template): (Requires <unistd.h> typically, but closely related to mktemp). Creates and opens a unique temporary file based on template (ending in XXXXXX), modifying template to the actual filename. Returns file descriptor. Much safer than mktemp.
    • EXIT_SUCCESS: Macro expanding to an integer constant indicating successful termination (usually 0).
    • EXIT_FAILURE: Macro expanding to an integer constant indicating unsuccessful termination (usually 1).
    • RAND_MAX: Macro defining the maximum value returned by rand().
  • <string.h> (String and Memory Operations)

    • Provides functions for manipulating arrays of characters (strings) and arbitrary blocks of memory.
    • size_t: Unsigned integer type for object sizes, counts. Also defined elsewhere.
    • NULL: Macro representing a null pointer constant. Also defined elsewhere.
    • void *memcpy(void *dest, const void *src, size_t n): Copy n bytes from memory area src to memory area dest. Behavior is undefined if src and dest overlap. Returns dest.
    • void *memmove(void *dest, const void *src, size_t n): Copy n bytes from memory area src to memory area dest. Areas may overlap (handles overlap correctly). Returns dest.
    • void *memset(void *s, int c, size_t n): Fill the first n bytes of the memory area s with the constant byte c (converted to unsigned char). Returns s. Often used to zero memory (e.g., memset(ptr, 0, size)).
    • int memcmp(const void *s1, const void *s2, size_t n): Compare the first n bytes of memory areas s1 and s2. Returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.
    • void *memchr(const void *s, int c, size_t n): Scan the first n bytes of memory area s for the first instance of byte c (converted to unsigned char). Returns pointer to the byte or NULL if not found.
    • size_t strlen(const char *s): Calculate the length of the null-terminated string s (excluding the null byte).
    • char *strcpy(char *dest, const char *src): UNSAFE! Copy the null-terminated string src to dest (including null terminator). No bounds checking! High risk of buffer overflows. Use strncpy (carefully) or snprintf. Returns dest.
    • char *strncpy(char *dest, const char *src, size_t n): Copy at most n bytes from string src to dest. Warning: If strlen(src) >= n, dest will not be null-terminated. Always ensure null termination manually if needed (e.g., dest[n-1] = '\0'; if n > 0). Returns dest.
    • char *strcat(char *dest, const char *src): UNSAFE! Append the null-terminated string src to the end of dest. No bounds checking on dest! High risk of buffer overflows. Use strncat. Returns dest.
    • char *strncat(char *dest, const char *src, size_t n): Append at most n bytes from string src to dest, plus a null terminator. Safer than strcat, but requires dest to have enough space for its original content, n bytes from src, and the null terminator. Always null-terminates (unlike strncpy). Returns dest.
    • int strcmp(const char *s1, const char *s2): Compare two null-terminated strings s1 and s2 lexicographically. Returns <0, 0, or >0.
    • int strncmp(const char *s1, const char *s2, size_t n): Compare at most n bytes (or until a null terminator) of strings s1 and s2. Returns <0, 0, or >0.
    • char *strchr(const char *s, int c): Find the first occurrence of the character c (converted to char) in the null-terminated string s. Returns pointer to the character in s or NULL if not found.
    • char *strrchr(const char *s, int c): Find the last occurrence of the character c (converted to char) in the null-terminated string s. Returns pointer or NULL.
    • char *strstr(const char *haystack, const char *needle): Find the first occurrence of the null-terminated substring needle within the null-terminated string haystack. Returns pointer to the beginning of the substring in haystack or NULL.
    • size_t strspn(const char *s, const char *accept): Calculate the length of the initial segment of s which consists only of characters found in accept.
    • size_t strcspn(const char *s, const char *reject): Calculate the length of the initial segment of s which consists only of characters not found in reject.
    • char *strpbrk(const char *s, const char *accept): Find the first character in s that matches any character specified in accept. Returns pointer to the character or NULL.
    • char *strtok(char *str, const char *delim): UNSAFE (Stateful/Not Reentrant)! Find tokens (substrings separated by delim) in str. Modifies str by inserting null bytes. Pass str on first call, NULL on subsequent calls to get next token. Not thread-safe. Use strtok_r (POSIX) if available. Returns pointer to token or NULL.
    • char *strerror(int errnum): Return a pointer to a string describing the error code errnum. The string may be statically allocated and overwritten by subsequent calls (potentially not thread-safe depending on implementation). Use strerror_r (POSIX) for thread-safety.
  • <stddef.h> (Standard Definitions)

    • Defines several fundamental types and macros used throughout the standard library, particularly related to sizes and pointers.
    • size_t: Unsigned integer type returned by sizeof operator, used for object sizes, memory allocation, array indexing, loop counts.
    • ptrdiff_t: Signed integer type capable of storing the result of subtracting two pointers.
    • NULL: Macro representing a null pointer constant (often (void*)0). Standard definition.
    • offsetof(type, member): Macro that calculates the byte offset of a member within a struct or union of type. Result is of type size_t.
  • <stdint.h> (Integer Types - C99 onwards)

    • Defines integer types with specific widths and other properties, promoting portability and clarity when exact sizes are needed.
    • int8_t, uint8_t: Signed/Unsigned 8-bit integer types (optional).
    • int16_t, uint16_t: Signed/Unsigned 16-bit integer types (optional).
    • int32_t, uint32_t: Signed/Unsigned 32-bit integer types (optional).
    • int64_t, uint64_t: Signed/Unsigned 64-bit integer types (optional).
    • int_least8_t, uint_least8_t: Smallest signed/unsigned type with at least 8 bits. (Similar for 16, 32, 64).
    • int_fast8_t, uint_fast8_t: Fastest signed/unsigned type with at least 8 bits. (Similar for 16, 32, 64).
    • intptr_t, uintptr_t: Signed/Unsigned integer types guaranteed to be large enough to hold a void* pointer without loss (optional).
    • intmax_t, uintmax_t: Largest supported signed/unsigned integer types.
    • INT8_MIN, INT8_MAX, UINT8_MAX: Macros for min/max values of fixed-width types (similar for 16, 32, 64).
    • SIZE_MAX: Macro defining the maximum value for size_t.
  • <errno.h> (System Error Numbers)

    • Defines the integer variable errno and macros for error codes reported by system calls and some library functions.
    • int errno: External integer variable (thread-local in modern multi-threaded environments) holding the last error code set by a failing system call or library function. Must include <errno.h> to use it. Value is only meaningful immediately after a function indicates failure (e.g., returns -1 or NULL).
    • Common errno value macros (represent error conditions):
      • EPERM: Operation not permitted.
      • ENOENT: No such file or directory.
      • EIO: Input/output error (often hardware or low-level).
      • E2BIG: Argument list too long.
      • EBADF: Bad file descriptor.
      • EAGAIN / EWOULDBLOCK: Resource temporarily unavailable / Operation would block (non-blocking I/O). Try again later.
      • ENOMEM: Not enough memory (Out of memory).
      • EACCES: Permission denied.
      • EFAULT: Bad address (invalid pointer passed).
      • EBUSY: Device or resource busy.
      • EEXIST: File exists.
      • EINVAL: Invalid argument provided to function.
      • ENOSPC: No space left on device.
      • EPIPE: Broken pipe (write to pipe/socket with no reader).
      • EINTR: Interrupted system call (often by a signal, may require retrying).
  • <unistd.h> (POSIX Operating System API)

    • Provides access to the POSIX operating system API, including I/O primitives (file descriptors), process control, user/group IDs, filesystem operations, and various system configuration constants. (Not part of standard C, but core to POSIX systems like Linux, macOS).
    • ssize_t: Signed integer type for byte counts returned by functions like read, write, recv (can hold -1 for errors). Defined in <sys/types.h> usually, often included.
    • off_t: Signed integer type for file sizes and offsets. Defined in <sys/types.h>.
    • pid_t: Signed integer type for process IDs (PID) and process group IDs. Defined in <sys/types.h>.
    • uid_t: Integer type for user IDs (UID). Defined in <sys/types.h>.
    • gid_t: Integer type for group IDs (GID). Defined in <sys/types.h>.
    • int read(int fd, void *buf, size_t count): Read up to count bytes from file descriptor fd into buf. Returns bytes read (0 on EOF), or -1 on error (check errno).
    • int write(int fd, const void *buf, size_t count): Write up to count bytes from buf to file descriptor fd. Returns bytes written, or -1 on error (check errno).
    • int close(int fd): Close the file descriptor fd. Returns 0 on success, -1 on error.
    • off_t lseek(int fd, off_t offset, int whence): Reposition the read/write file offset of the open file descriptor fd. whence is SEEK_SET, SEEK_CUR, SEEK_END. Returns resulting offset from beginning of file, or -1 on error.
    • pid_t fork(void): Create a new child process which is a duplicate of the calling (parent) process. Returns child's PID in parent, 0 in child, -1 on error.
    • int execve(const char *pathname, char *const argv[], char *const envp[]): Replace the current process image with a new one loaded from pathname. argv is the argument list (null-terminated array), envp is the environment (null-terminated array). Does not return on success. Returns -1 on error. The core exec function.
    • int execv(const char *pathname, char *const argv[]): Like execve, uses current environment.
    • int execvp(const char *file, char *const argv[]): Like execv, but searches PATH environment variable for file if it doesn't contain a slash. Common variant.
    • int execl(const char *pathname, const char *arg, ... /*, (char *) NULL */): List-based variant of exec, takes arguments as separate const char* parameters, terminated by NULL. Uses current environment.
    • int execlp(const char *file, const char *arg, ... /*, (char *) NULL */): List-based variant like execl, but searches PATH like execvp.
    • pid_t getpid(void): Get the process ID (PID) of the calling process.
    • pid_t getppid(void): Get the parent process ID (PPID) of the calling process.
    • uid_t getuid(void): Get the real user ID (UID) of the calling process.
    • uid_t geteuid(void): Get the effective user ID (EUID) of the calling process.
    • gid_t getgid(void): Get the real group ID (GID) of the calling process.
    • gid_t getegid(void): Get the effective group ID (EGID) of the calling process.
    • void _exit(int status): Terminate the calling process immediately without calling exit handlers (atexit) or flushing stdio buffers. status is exit code (low 8 bits available to parent via wait). Usually called by exit().
    • unsigned int alarm(unsigned int seconds): Arrange for SIGALRM signal to be delivered to the process in seconds. If seconds is 0, cancels pending alarm. Returns seconds remaining on previous alarm, or 0.
    • int pause(void): Suspend the process until a signal is caught whose action is to terminate or call a handler. Returns -1 with errno set to EINTR.
    • unsigned int sleep(unsigned int seconds): Suspend execution for the specified number of seconds, or until a signal is delivered that terminates the process or triggers a handler. Returns seconds left unslept (if interrupted), or 0.
    • int usleep(useconds_t usec): DEPRECATED (in POSIX.1-2001, removed in 2008). Suspend execution for usec microseconds. Use nanosleep instead. May interact poorly with signals.
    • int pipe(int pipefd[2]): Create a pipe, a unidirectional data channel. pipefd[0] is for reading, pipefd[1] is for writing. Returns 0 on success, -1 on error.
    • int dup(int oldfd): Duplicate an existing file descriptor oldfd, returning the lowest unused non-negative descriptor. Returns new fd or -1.
    • int dup2(int oldfd, int newfd): Duplicate oldfd to newfd, closing newfd first if necessary. If oldfd == newfd, does nothing. Returns newfd or -1.
    • int unlink(const char *pathname): Remove a name (link) from the filesystem. If it's the last link and no processes have the file open, the file data is deleted. Used to delete files. Returns 0 on success, -1 on error.
    • int rmdir(const char *pathname): Remove an empty directory. Returns 0 on success, -1 on error.
    • int chdir(const char *path): Change the current working directory to path. Returns 0 on success, -1 on error.
    • char *getcwd(char *buf, size_t size): Copy the absolute pathname of the current working directory to buf (up to size bytes). If buf is NULL, allocates buffer (needs free). Returns buf or NULL on error.
    • char *getwd(char *buf): UNSAFE! DEPRECATED! Get current working directory into buf. Cannot specify buffer size, potential overflow. Use getcwd.
    • int chown(const char *pathname, uid_t owner, gid_t group): Change the owner and group of a file specified by pathname. Use -1 for owner/group to leave unchanged. Returns 0 on success, -1 on error. (lchown changes symlink itself, fchown uses fd).
    • int access(const char *pathname, int mode): Check user's permissions for a file. mode is bitwise OR of R_OK, W_OK, X_OK (test permissions), or F_OK (test existence). Warning: Potential Time-of-check to time-of-use (TOCTOU) race condition security vulnerability. Returns 0 if access allowed, -1 otherwise.
    • long sysconf(int name): Get system configuration values at runtime (e.g., _SC_PAGESIZE, _SC_NPROCESSORS_ONLN). Returns value or -1 on error.
    • int isatty(int fd): Check if file descriptor fd refers to a terminal. Returns 1 if it is, 0 otherwise (setting errno if error occurs).
    • int link(const char *oldpath, const char *newpath): Create a new hard link newpath for the existing file oldpath. Returns 0 on success, -1 on error.
    • int symlink(const char *target, const char *linkpath): Create a symbolic link named linkpath containing the string target. Returns 0 on success, -1 on error.
    • ssize_t readlink(const char *pathname, char *buf, size_t bufsiz): Read the value of a symbolic link pathname into buf (up to bufsiz bytes). Does not null-terminate buf. Returns bytes read or -1.
  • <fcntl.h> (File Control Operations)

    • Defines functions and constants for manipulating file descriptors, such as opening files (open), modifying their properties (fcntl), and locking. (POSIX header).
    • int open(const char *pathname, int flags, ... /* mode_t mode */): Open or create a file, returning a non-negative file descriptor (fd). flags is bitwise OR of access modes (O_RDONLY, O_WRONLY, O_RDWR) and creation/status flags (O_CREAT, O_TRUNC, O_APPEND, O_NONBLOCK, O_CLOEXEC, etc.). Optional mode argument (e.g., 0644) is required only when O_CREAT is specified, sets initial permissions (modified by umask). Returns fd or -1 on error.
    • int creat(const char *pathname, mode_t mode): DEPRECATED. Equivalent to open(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode). Use open directly.
    • int fcntl(int fd, int cmd, ... /* arg */): Perform various operations (cmd) on file descriptor fd. Common commands:
      • F_DUPFD: Duplicate fd (like dup, but to lowest >= arg).
      • F_GETFD/F_SETFD: Get/set fd flags (e.g., FD_CLOEXEC). arg is int.
      • F_GETFL/F_SETFL: Get/set file status flags (e.g., O_APPEND, O_NONBLOCK). arg is int.
      • F_GETLK/F_SETLK/F_SETLKW: Get/Set/Set-and-wait for file locks. arg is struct flock *.
    • Common open/fcntl flags:
      • O_RDONLY: Open for reading only.
      • O_WRONLY: Open for writing only.
      • O_RDWR: Open for reading and writing.
      • O_APPEND: Append data to the end of the file.
      • O_CREAT: Create file if it does not exist.
      • O_EXCL: Used with O_CREAT, ensures open fails if file exists (atomic check).
      • O_TRUNC: Truncate existing file to zero length if opened for writing.
      • O_NONBLOCK: Open in non-blocking mode (I/O calls return immediately, possibly with EAGAIN/EWOULDBLOCK).
      • O_CLOEXEC: Set the close-on-exec flag for the new file descriptor (atomically). Prevents fd leakage across exec.
    • FD_CLOEXEC: File descriptor flag (for F_GETFD/F_SETFD) indicating fd should be closed automatically upon exec.
  • <sys/stat.h> (File Status and Information)

    • Defines the stat structure used to hold file metadata, functions to retrieve this information (stat, fstat, lstat), and functions for creating directories/FIFOs and changing file modes. (POSIX header).
    • struct stat: Structure holding file metadata (device ID, inode number, mode/permissions, link count, user ID, group ID, size, access time, modification time, status change time, block size, block count).
    • mode_t: Integer type for file modes/permissions. Defined in <sys/types.h>.
    • int stat(const char *pathname, struct stat *statbuf): Get file status for pathname (follows symbolic links) and store it in statbuf. Returns 0 on success, -1 on error.
    • int fstat(int fd, struct stat *statbuf): Get file status for the open file descriptor fd. Returns 0 on success, -1 on error.
    • int lstat(const char *pathname, struct stat *statbuf): Get file status for pathname. If pathname is a symbolic link, stats the link itself, not the file it points to. Returns 0 on success, -1 on error.
    • int mkdir(const char *pathname, mode_t mode): Create a new directory named pathname with specified initial mode (permissions, modified by the process's umask). Returns 0 on success, -1 on error.
    • int chmod(const char *pathname, mode_t mode): Change the permissions (mode) of file pathname. Returns 0 on success, -1 on error. (fchmod operates on an fd).
    • mode_t umask(mode_t mask): Set the process's file mode creation mask and return the previous mask. Bits set in mask are cleared from the mode specified in open or mkdir.
    • File type macros (for testing st_mode field):
      • S_ISREG(m): Is it a regular file?
      • S_ISDIR(m): Is it a directory?
      • S_ISCHR(m): Is it a character device?
      • S_ISBLK(m): Is it a block device?
      • S_ISFIFO(m): Is it a FIFO (named pipe)?
      • S_ISLNK(m): Is it a symbolic link? (Use lstat to get mode for link itself).
      • S_ISSOCK(m): Is it a socket?
    • Permission bits (for st_mode field and mode arguments to open/chmod/mkdir):
      • S_IRUSR, S_IWUSR, S_IXUSR: User (owner) read, write, execute.
      • S_IRGRP, S_IWGRP, S_IXGRP: Group read, write, execute.
      • S_IROTH, S_IWOTH, S_IXOTH: Others read, write, execute.
      • S_ISUID: Set-user-ID bit.
      • S_ISGID: Set-group-ID bit.
      • S_ISVTX: Sticky bit.
  • <sys/types.h> (Primitive System Data Types)

    • Defines various basic data types used in system calls and other POSIX headers. Often included implicitly by other headers like <unistd.h> or <sys/stat.h>. (POSIX header).
    • size_t: Unsigned integer type for sizes. Also in <stddef.h>.
    • ssize_t: Signed integer type for byte counts or errors (-1).
    • pid_t: Signed integer type for process IDs (PID) and process group IDs.
    • uid_t: Integer type for user IDs (UID).
    • gid_t: Integer type for group IDs (GID).
    • off_t: Signed integer type for file sizes and offsets (used by lseek).
    • mode_t: Integer type for file modes/permissions (used by stat, chmod, mkdir, open).
    • dev_t: Type for device IDs (st_dev).
    • ino_t: Type for inode numbers (st_ino).
    • nlink_t: Type for link counts (st_nlink).
    • time_t: Type for time in seconds. Also in <time.h>.
  • <signal.h> (Signal Handling)

    • Provides facilities for handling asynchronous signals (interrupts, exceptions, notifications) that can be delivered to a process.
    • sig_atomic_t: Integer type that can be accessed atomically, suitable for simple communication with signal handlers (assignments must be single, indivisible operations).
    • sigset_t: Type representing a set of signals (used for blocking/unblocking).
    • struct sigaction: Structure used with sigaction to specify signal handling details (handler function, signal mask to block during handler execution, flags).
    • typedef void (*sighandler_t)(int); (Conceptual type, actual definition varies) The type of a signal handler function, taking the signal number as an argument.
    • int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact): Examine and change the action for signal signum. act specifies the new action, oldact (if non-NULL) receives the previous action. The preferred, portable, and more powerful way to handle signals. Returns 0 on success, -1 on error.
    • sighandler_t signal(int signum, sighandler_t handler): UNRELIABLE/NON-PORTABLE (historically). Set the disposition (handler) for signal signum. handler can be SIG_DFL (default), SIG_IGN (ignore), or a function pointer. Semantics vary across systems (especially regarding handler re-installation). Use sigaction instead for reliable behavior. Returns previous handler or SIG_ERR on error.
    • int kill(pid_t pid, int sig): Send signal sig to process pid. Special pid values: >0 (specific process), 0 (current process group), -1 (all processes with permission), <-1 (process group abs(pid)). Returns 0 on success, -1 on error.
    • int raise(int sig): Send signal sig to the calling process or thread. Equivalent to kill(getpid(), sig). Returns 0 on success, non-zero on error.
    • int sigemptyset(sigset_t *set): Initialize the signal set set to be empty (exclude all signals). Returns 0 on success, -1 on error.
    • int sigfillset(sigset_t *set): Initialize the signal set set to be full (include all signals). Returns 0 on success, -1 on error.
    • int sigaddset(sigset_t *set, int signum): Add signal signum to the signal set set. Returns 0 on success, -1 on error.
    • int sigdelset(sigset_t *set, int signum): Remove signal signum from the signal set set. Returns 0 on success, -1 on error.
    • int sigismember(const sigset_t *set, int signum): Test if signum is a member of the signal set set. Returns 1 if member, 0 if not, -1 on error.
    • int sigprocmask(int how, const sigset_t *set, sigset_t *oldset): Examine and/or change the calling thread's signal mask (the set of currently blocked signals). how: SIG_BLOCK (add set to mask), SIG_UNBLOCK (remove set from mask), SIG_SETMASK (set mask to set). If oldset is non-NULL, the previous mask is stored there. Returns 0 on success, -1 on error.
    • int sigpending(sigset_t *set): Examine the set of signals that are currently blocked and pending for delivery to the calling thread. Stores the set in set. Returns 0 on success, -1 on error.
    • int sigsuspend(const sigset_t *mask): Atomically set the signal mask to mask and suspend the process until a signal is caught (whose action isn't ignore) or terminates the process. Restores original mask on return. Returns -1 with errno EINTR.
    • Handler Macros:
      • SIG_DFL: Specifies the default action for the signal.
      • SIG_IGN: Specifies that the signal should be ignored.
      • SIG_ERR: Return value from signal indicating an error.
    • Common Signal Macros (partial list, behavior can vary):
      • SIGHUP: Hangup detected on controlling terminal or death of controlling process.
      • SIGINT: Interrupt from keyboard (Ctrl+C).
      • SIGQUIT: Quit from keyboard (Ctrl+).
      • SIGILL: Illegal Instruction.
      • SIGABRT: Abort signal (e.g., from abort()).
      • SIGFPE: Floating point exception.
      • SIGKILL: Kill signal (cannot be caught or ignored).
      • SIGSEGV: Segmentation fault (invalid memory reference).
      • SIGPIPE: Broken pipe (write to pipe/socket with no readers).
      • SIGALRM: Timer signal from alarm().
      • SIGTERM: Termination signal (polite request to terminate).
      • SIGCHLD: Child process stopped or terminated.
      • SIGUSR1, SIGUSR2: User-defined signals.
  • <sys/wait.h> (Process Waiting)

    • Defines functions and macros for waiting for child processes to change state (terminate, stop) and retrieving information about their status. Essential for preventing zombie processes. (POSIX header).
    • pid_t wait(int *wstatus): Wait for any child process to change state (terminate, stop, continue). Blocks until a child changes state. If wstatus is not NULL, stores status information there. Returns PID of the child whose state changed, or -1 on error (e.g., no children). Equivalent to waitpid(-1, wstatus, 0).
    • pid_t waitpid(pid_t pid, int *wstatus, int options): Wait for a specific child process or group of children to change state.
      • pid > 0: Wait for the specific child with PID pid.
      • pid == -1: Wait for any child process (like wait).
      • pid == 0: Wait for any child in the calling process's process group.
      • pid < -1: Wait for any child in the process group abs(pid).
      • options: Bitwise OR of flags, e.g., WNOHANG (return immediately if no child has changed state), WUNTRACED (also return if child is stopped), WCONTINUED (also return if stopped child is continued).
      • Returns PID of child, 0 (if WNOHANG and no change), or -1 on error.
    • Wait status analysis macros (used with the wstatus value):
      • WIFEXITED(wstatus): Returns true (non-zero) if the child terminated normally (via exit() or return from main).
      • WEXITSTATUS(wstatus): If WIFEXITED is true, returns the low 8 bits of the child's exit status.
      • WIFSIGNALED(wstatus): Returns true if the child was terminated by a signal.
      • WTERMSIG(wstatus): If WIFSIGNALED is true, returns the number of the signal that terminated the child.
      • WIFSTOPPED(wstatus): Returns true if the child was stopped by a signal (requires WUNTRACED or WCONTINUED in waitpid).
      • WSTOPSIG(wstatus): If WIFSTOPPED is true, returns the number of the signal that stopped the child.
      • WIFCONTINUED(wstatus): Returns true if the child was resumed by SIGCONT (requires WCONTINUED).
  • <time.h> (Time and Date Functions)

    • Provides types and functions for manipulating time and date information.
    • time_t: Arithmetic type capable of representing time (usually seconds since the Epoch: 00:00:00 UTC, Jan 1, 1970).
    • struct tm: Structure holding broken-down calendar time:
      • int tm_sec: Seconds (0-60; 60 allows for leap seconds).
      • int tm_min: Minutes (0-59).
      • int tm_hour: Hours (0-23).
      • int tm_mday: Day of the month (1-31).
      • int tm_mon: Month (0-11; January = 0).
      • int tm_year: Year since 1900.
      • int tm_wday: Day of the week (0-6; Sunday = 0).
      • int tm_yday: Day of the year (0-365).
      • int tm_isdst: Daylight Saving Time flag (>0 if DST in effect, 0 if not, <0 if info unavailable).
    • clock_t: Arithmetic type representing processor time.
    • time_t time(time_t *tloc): Get current calendar time as time_t (seconds since the Epoch). If tloc is not NULL, the value is also stored there. Returns current time or (time_t)-1 on error.
    • struct tm *localtime(const time_t *timep): Convert time_t value timep into broken-down time struct tm expressed in the system's local timezone. Warning: Returns pointer to a static internal buffer, which may be overwritten by subsequent calls to localtime or gmtime. Not thread-safe. Use localtime_r (POSIX) for thread-safety.
    • struct tm *gmtime(const time_t *timep): Convert time_t value timep into broken-down time struct tm expressed in Coordinated Universal Time (UTC, often called GMT). Warning: Returns pointer to static data, not thread-safe. Use gmtime_r (POSIX).
    • time_t mktime(struct tm *tm): Convert broken-down local time struct tm (fields tm_wday and tm_yday are ignored, others normalized) into time_t calendar time value. Returns time_t value or (time_t)-1 if it cannot be represented. Modifies the tm struct, filling in tm_wday and tm_yday.
    • size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *tm): Format the broken-down time tm into the string s (up to maxsize bytes, including null) according to format specifiers (e.g., %Y year, %m month, %d day, %H hour, %M min, %S sec, %Z timezone name). Returns number of bytes written (excluding null) or 0 if maxsize was too small.
    • char *asctime(const struct tm *tm): Convert struct tm into a standard C string format (e.g., "Wed Jun 30 21:49:08 1993\n"). Warning: Returns pointer to static data, not thread-safe. Use strftime.
    • char *ctime(const time_t *timep): Convert time_t into a standard C string format (like asctime). Equivalent to asctime(localtime(timep)). Warning: Returns pointer to static data, not thread-safe.
    • double difftime(time_t time1, time_t time0): Calculate the difference in seconds between two time_t values (time1 - time0), returned as a double.
    • clock_t clock(void): Return the processor time consumed by the program since invocation, measured in clock_t units. Divide by CLOCKS_PER_SEC to get seconds. May wrap. Quality/granularity varies.
    • CLOCKS_PER_SEC: Macro defining the number of clock_t ticks per second.
  • <sys/time.h> (Time Operations - High Resolution)

    • Provides structures and functions for more precise time measurements (microseconds). Often included by <time.h> on POSIX systems, but standard requires explicit include for gettimeofday. (POSIX header).
    • struct timeval: Structure holding time with microsecond resolution:
      • time_t tv_sec: Seconds.
      • suseconds_t tv_usec: Microseconds.
    • struct timezone: OBSOLETE. Structure formerly used with gettimeofday for timezone information. Do not use; pass NULL for the tz argument.
    • int gettimeofday(struct timeval *tv, struct timezone *tz): Get the current time as seconds and microseconds since the Epoch. tz argument is obsolete and should be NULL. Returns 0 on success, -1 on error. Still very common, though POSIX favors clock_gettime from <time.h> (if available with CLOCK_REALTIME).
  • <math.h> (Mathematical Functions)

    • Provides common mathematical functions, primarily operating on double floating-point numbers.
    • double sqrt(double x): Compute the non-negative square root of x (x >= 0).
    • double pow(double base, double exp): Compute base raised to the power exp (base^exp). Handles various edge cases (0, infinity, NaN).
    • double fabs(double x): Compute the absolute value of floating-point number x. (fabsf for float, fabsl for long double).
    • double fmod(double x, double y): Compute floating-point remainder of x/y. Result has the same sign as x.
    • double exp(double x): Compute e (Euler's number, ~2.718) raised to the power x (e^x).
    • double log(double x): Compute the natural logarithm (base e) of x (x > 0).
    • double log10(double x): Compute the base-10 logarithm of x (x > 0).
    • double sin(double x), double cos(double x), double tan(double x): Compute sine, cosine, tangent of x (where x is in radians).
    • double asin(double x), double acos(double x), double atan(double x): Compute arc sine (x in [-1,1]), arc cosine (x in [-1,1]), arc tangent of x. Results are in radians.
    • double atan2(double y, double x): Compute arc tangent of y/x, using the signs of x and y to determine the correct quadrant for the result (in radians, range [-pi, pi]).
    • double ceil(double x): Round x upward to the nearest integer value (returned as double). "Ceiling".
    • double floor(double x): Round x downward to the nearest integer value (returned as double). "Floor".
    • double round(double x): (C99) Round x to the nearest integer value (returned as double), rounding halfway cases away from zero.
    • double trunc(double x): (C99) Round x toward zero to the nearest integer value (returned as double).
    • double hypot(double x, double y): (C99) Compute sqrt(x*x + y*y) accurately, avoiding intermediate overflow/underflow.
    • HUGE_VAL, HUGE_VALF, HUGE_VALL: Macros representing large positive floating-point values (often infinity). Used as error returns.
    • INFINITY: (C99) Macro representing positive infinity (float type).
    • NAN: (C99) Macro representing a "Not a Number" floating-point value (float type).
    • fpclassify(x), isfinite(x), isinf(x), isnan(x), isnormal(x), signbit(x): (C99) Macros for classifying floating-point values.
  • <ctype.h> (Character Classification and Conversion)

    • Provides functions for testing characters against various classifications (digit, letter, whitespace, etc.) and for converting between uppercase and lowercase. Functions take int argument but typically operate on values representable as unsigned char or EOF.
    • int isalnum(int c): Check if c is alphanumeric (isalpha or isdigit).
    • int isalpha(int c): Check if c is an alphabetic character (isupper or islower).
    • int iscntrl(int c): Check if c is a control character.
    • int isdigit(int c): Check if c is a decimal digit ('0'-'9').
    • int isgraph(int c): Check if c is any printable character except space.
    • int islower(int c): Check if c is a lowercase letter.
    • int isprint(int c): Check if c is a printable character (including space).
    • int ispunct(int c): Check if c is a punctuation character (printable, not space or isalnum).
    • int isspace(int c): Check if c is whitespace (space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v').
    • int isupper(int c): Check if c is an uppercase letter.
    • int isxdigit(int c): Check if c is a hexadecimal digit ('0'-'9', 'a'-'f', 'A'-'F').
    • int tolower(int c): Convert uppercase letter c to lowercase. Returns c unchanged if not uppercase.
    • int toupper(int c): Convert lowercase letter c to uppercase. Returns c unchanged if not lowercase.
  • <stdbool.h> (Boolean Type and Values - C99 onwards)

    • Defines a boolean type and constants true and false for improved code clarity. Often implemented via macros that expand to integer types/values.
    • bool: Macro expanding to the boolean type (_Bool typically).
    • true: Macro expanding to the boolean true value (typically 1).
    • false: Macro expanding to the boolean false value (typically 0).
    • __bool_true_false_are_defined: Macro defined to 1 when the header is included.
  • <limits.h> (Limits of Fundamental Integer Types)

    • Defines macros specifying the limits (minimum and maximum values) for the standard fundamental integer types like char, int, short, long.
    • CHAR_BIT: Number of bits in a char.
    • CHAR_MIN, CHAR_MAX: Minimum/Maximum value for char.
    • SCHAR_MIN, SCHAR_MAX: Minimum/Maximum value for signed char.
    • UCHAR_MAX: Maximum value for unsigned char.
    • SHRT_MIN, SHRT_MAX: Minimum/Maximum value for short int.
    • USHRT_MAX: Maximum value for unsigned short int.
    • INT_MIN, INT_MAX: Minimum/Maximum value for int.
    • UINT_MAX: Maximum value for unsigned int.
    • LONG_MIN, LONG_MAX: Minimum/Maximum value for long int.
    • ULONG_MAX: Maximum value for unsigned long int.
    • LLONG_MIN, LLONG_MAX: (C99) Minimum/Maximum value for long long int.
    • ULLONG_MAX: (C99) Maximum value for unsigned long long int.
  • <assert.h> (Debugging Assertions)

    • Provides the assert macro, used for inserting run-time sanity checks during development.
    • void assert(scalar expression): If the macro NDEBUG is not defined at the point of inclusion of <assert.h>, assert evaluates expression. If expression is false (evaluates to 0), assert prints an error message (including the expression text, file name, and line number) to stderr and then calls abort(). If NDEBUG is defined, the assert macro expands to nothing ((void)0), effectively disabling the check for release builds.
  • <stdarg.h> (Variable Argument Lists)

    • Provides macros for implementing functions that accept a variable number of arguments (like printf or scanf).
    • va_list: Type suitable for holding information needed by va_start, va_arg, and va_end.
    • void va_start(va_list ap, last): Initializes ap for use by va_arg and va_end. last must be the name of the last fixed parameter before the variable arguments (...). Must be called before first va_arg.
    • type va_arg(va_list ap, type): Expands to an expression that has the type and value of the next argument in the call. ap must have been initialized by va_start. type is the expected type of the next argument. Behavior undefined if no next argument or if type is incompatible. Modifies ap.
    • void va_end(va_list ap): Performs necessary cleanup for ap after all arguments have been processed. Must be called before the function returns if va_start was called.
    • void va_copy(va_list dest, va_list src): (C99) Creates a copy dest of the current variable argument list state src. Useful if the list needs to be scanned more than once. dest must also be passed to va_end.
  • <sys/socket.h> (Core Socket Functions and Structures)

    • Defines the primary functions and structures for network socket programming (creating sockets, binding addresses, connecting, listening, sending, receiving). (POSIX/BSD Sockets API header).
    • int socket(int domain, int type, int protocol): Create a communication endpoint (socket).
      • domain: Communication domain (e.g., AF_INET for IPv4, AF_INET6 for IPv6, AF_UNIX for local).
      • type: Communication semantics (e.g., SOCK_STREAM for reliable stream/TCP, SOCK_DGRAM for datagram/UDP, SOCK_RAW for raw network protocol access). Add SOCK_NONBLOCK, SOCK_CLOEXEC (Linux extensions) for atomic setting.
      • protocol: Specific protocol (usually 0 to select default for domain/type).
      • Returns socket file descriptor (a small non-negative integer) or -1 on error.
    • int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen): Assign a local address/port (addr) to the socket sockfd. Typically used on the server side before listen or for specific client-side source address/port. Returns 0 on success, -1 on error.
    • int listen(int sockfd, int backlog): Mark sockfd (which must be of type SOCK_STREAM or SOCK_SEQPACKET) as a passive socket that will be used to accept incoming connection requests. backlog suggests the maximum queue length for pending connections. Returns 0 on success, -1 on error.
    • int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen): For a listening socket sockfd, extract the first connection request on the queue, create a new connected socket for this specific connection, and return its file descriptor. If addr and addrlen are non-NULL, they are filled with the address of the connecting peer (client). addrlen is value-result: initialize it to sizeof(*addr) before the call. Blocks by default until a connection arrives. Returns new socket fd or -1 on error. (Linux extension: accept4 adds flags like SOCK_NONBLOCK, SOCK_CLOEXEC).
    • int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen): Initiate a connection on socket sockfd (client side) to the server address specified by addr. Returns 0 on success, -1 on error (connection may be asynchronous for non-blocking sockets).
    • ssize_t send(int sockfd, const void *buf, size_t len, int flags): Send len bytes from buf on a connected socket sockfd. flags modify behavior (e.g., MSG_NOSIGNAL on Linux prevents SIGPIPE). Returns number of bytes sent (can be less than len) or -1 on error.
    • ssize_t recv(int sockfd, void *buf, size_t len, int flags): Receive up to len bytes into buf from a connected socket sockfd. flags modify behavior (e.g., MSG_PEEK looks at data without consuming). Returns number of bytes received, 0 if peer shut down connection gracefully, or -1 on error.
    • ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen): Send len bytes from buf on socket sockfd (can be connected or unconnected, typically UDP) to the specific destination address dest_addr. Returns bytes sent or -1.
    • ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen): Receive up to len bytes into buf from socket sockfd. If src_addr and addrlen are non-NULL, they are filled with the address of the sender. addrlen is value-result. Returns bytes received, 0 on shutdown (if connected), or -1.
    • int shutdown(int sockfd, int how): Gracefully disable sends and/or receives on a connected socket sockfd.
      • how: SHUT_RD (disable further receives), SHUT_WR (disable further sends, sends FIN), SHUT_RDWR (both).
      • Returns 0 on success, -1 on error. Different from close() which releases the fd.
    • int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen): Get options for socket sockfd. level indicates protocol level (e.g., SOL_SOCKET, IPPROTO_TCP). optname is the option name (e.g., SO_REUSEADDR, SO_ERROR, TCP_NODELAY). Value stored in optval, length in optlen (value-result). Returns 0 or -1.
    • int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen): Set options for socket sockfd. Parameters similar to getsockopt. Returns 0 or -1.
    • struct sockaddr: Generic socket address structure (base type, contains sa_family). Actual specific address structures (sockaddr_in, sockaddr_in6) are cast to this.
    • struct sockaddr_storage: Generic socket address structure guaranteed to be large enough to hold any supported address type. Useful for writing protocol-agnostic code, avoids guessing buffer sizes needed for accept or recvfrom. Contains ss_family.
    • socklen_t: Unsigned integer type used for socket address structure lengths (passed to bind, connect, accept, getsockname, getpeername, getsockopt, setsockopt, etc.).
    • Socket domain constants: AF_INET (IPv4), AF_INET6 (IPv6), AF_UNIX / AF_LOCAL (Local IPC).
    • Socket type constants: SOCK_STREAM (TCP), SOCK_DGRAM (UDP), SOCK_SEQPACKET (Sequenced, reliable datagrams), SOCK_RAW (Raw network layer access).
    • Socket level constant (for getsockopt/setsockopt): SOL_SOCKET (generic socket options).
    • Common socket options (optname for SOL_SOCKET): SO_REUSEADDR (allow reuse of local address/port), SO_KEEPALIVE (enable keep-alive probes), SO_BROADCAST (allow sending broadcast messages), SO_ERROR (get pending error and clear), SO_RCVBUF / SO_SNDBUF (receive/send buffer sizes), SO_RCVTIMEO / SO_SNDTIMEO (receive/send timeouts).
    • int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen): Get the local address/port bound to sockfd.
    • int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen): Get the remote address/port connected to sockfd.
  • <netinet/in.h> (Internet Address Family - IPv4/IPv6)

    • Defines structures and constants specific to the Internet Protocol suite (IPv4, IPv6), including socket address structures and byte order conversion functions. (POSIX/Sockets header).
    • struct sockaddr_in: Socket address structure for IPv4. Contains:
      • sa_family_t sin_family: Address family (AF_INET).
      • in_port_t sin_port: Port number (in network byte order).
      • struct in_addr sin_addr: IPv4 address (in network byte order).
    • struct in_addr: Structure holding an IPv4 address. Contains:
      • uint32_t s_addr: The 32-bit IPv4 address (network byte order).
    • struct sockaddr_in6: Socket address structure for IPv6. Contains:
      • sa_family_t sin6_family: Address family (AF_INET6).
      • in_port_t sin6_port: Port number (network byte order).
      • uint32_t sin6_flowinfo: Flow information (network byte order).
      • struct in6_addr sin6_addr: IPv6 address (network byte order).
      • uint32_t sin6_scope_id: Scope ID (for link-local addresses).
    • struct in6_addr: Structure holding an IPv6 address. Contains:
      • uint8_t s6_addr[16]: The 128-bit IPv6 address (network byte order array).
    • uint16_t htons(uint16_t hostshort): Convert 16-bit value (short) from host byte order to network byte order (Big Endian). "Host TO Network Short". Used for port numbers.
    • uint32_t htonl(uint32_t hostlong): Convert 32-bit value (long, typically) from host byte order to network byte order. "Host TO Network Long". Used for IPv4 addresses.
    • uint16_t ntohs(uint16_t netshort): Convert 16-bit value from network byte order to host byte order. "Network TO Host Short".
    • uint32_t ntohl(uint32_t netlong): Convert 32-bit value from network byte order to host byte order. "Network TO Host Long".
    • Protocol number constants (for socket protocol field or getprotobyname): IPPROTO_IP, IPPROTO_TCP, IPPROTO_UDP, IPPROTO_IPV6, IPPROTO_ICMP.
    • INADDR_ANY: IPv4 wildcard address (0.0.0.0) for binding (use htonl(INADDR_ANY)).
    • INADDR_LOOPBACK: IPv4 loopback address (127.0.0.1) (use htonl(INADDR_LOOPBACK)).
    • in6addr_any: (const struct in6_addr) IPv6 wildcard address (::) for binding.
    • in6addr_loopback: (const struct in6_addr) IPv6 loopback address (::1).
  • <arpa/inet.h> (Internet Operations - String Conversion)

    • Provides functions for converting internet addresses between presentation (text string) format and network (binary) format. (POSIX/Sockets header).
    • int inet_pton(int af, const char *src, void *dst): Convert IP address string src (e.g., "192.0.2.1" or "2001:db8::1") in presentation format to binary network address format (stored in dst, which should be a struct in_addr * for AF_INET or struct in6_addr * for AF_INET6). af specifies the address family. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns 1 on success, 0 if src is not a valid address string for af, -1 on error (errno set).
    • const char *inet_ntop(int af, const void *src, char *dst, socklen_t size): Convert binary network address src (struct in_addr * or struct in6_addr *) to presentation format string dst. size is the size of the dst buffer. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns pointer to dst on success, NULL on error (errno set, e.g., ENOSPC if size too small). Use INET_ADDRSTRLEN and INET6_ADDRSTRLEN (defined in <netinet/in.h>) for adequate buffer sizes.
    • in_addr_t inet_addr(const char *cp): DEPRECATED/UNSAFE! Convert IPv4 address string cp (dotted-decimal) to binary uint32_t in network byte order. Returns INADDR_NONE ((in_addr_t)-1) on error, but this is also a valid broadcast address (255.255.255.255), making error detection ambiguous. Only handles IPv4. Use inet_pton.
    • char *inet_ntoa(struct in_addr in): DEPRECATED/UNSAFE! Convert binary IPv4 address in (network byte order) to dotted-decimal string. Warning: Returns pointer to a static internal buffer, which is overwritten by subsequent calls. Not thread-safe. Only handles IPv4. Use inet_ntop.
  • <netdb.h> (Network Database Operations - Hostname/Service Lookup)

    • Provides functions for translating between hostnames/service names and network addresses/port numbers, querying the network databases (like /etc/hosts, DNS, /etc/services). (POSIX/Sockets header).
    • struct addrinfo: Structure used by getaddrinfo to hold address information and hints:
      • int ai_flags: Input hints flags (e.g., AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST, AI_NUMERICSERV).
      • int ai_family: Address family (AF_INET, AF_INET6, AF_UNSPEC).
      • int ai_socktype: Socket type (SOCK_STREAM, SOCK_DGRAM, 0).
      • int ai_protocol: Protocol (IPPROTO_TCP, IPPROTO_UDP, 0).
      • socklen_t ai_addrlen: Length of ai_addr.
      • struct sockaddr *ai_addr: Pointer to socket address structure.
      • char *ai_canonname: Pointer to canonical hostname (if AI_CANONNAME requested).
      • struct addrinfo *ai_next: Pointer to next structure in linked list.
    • int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res): The modern, recommended function for network address and service translation. Resolves hostname (node, e.g., "www.example.com" or IP string) and service name (service, e.g., "http" or "80") into one or more addrinfo structures, returned as a linked list via res. hints provides criteria (family, socktype, flags) for the lookup. Handles IPv4/IPv6 seamlessly based on system configuration and hints. The returned structures are suitable for passing directly to socket, bind, connect. Returns 0 on success, non-zero error code (use gai_strerror to convert to string) on failure.
    • void freeaddrinfo(struct addrinfo *res): Free the linked list of addrinfo structures allocated and returned by getaddrinfo. Must be called to prevent memory leaks.
    • const char *gai_strerror(int errcode): Convert the error code returned by getaddrinfo into a human-readable string.
    • struct hostent *gethostbyname(const char *name): DEPRECATED. Look up host name (hostname or IPv4 dotted-decimal). Returns pointer to static hostent structure containing addresses, aliases, etc. Only reliably handles IPv4. Not thread-safe. Use getaddrinfo.
    • struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type): DEPRECATED. Reverse lookup: find hostname for binary address addr. Only AF_INET (type) usually supported. Returns pointer to static hostent. Not thread-safe. Use getnameinfo or getaddrinfo.
    • struct servent *getservbyname(const char *name, const char *proto): DEPRECATED. Look up service name (e.g., "http") for a given protocol (proto, e.g., "tcp"). Returns pointer to static servent structure containing port number. Not thread-safe. Use getaddrinfo.
    • int getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, socklen_t hostlen, char *serv, socklen_t servlen, int flags): The modern reverse lookup function. Translate socket address sa back into hostname (stored in host) and service name (stored in serv). flags control lookup behavior (e.g., NI_NUMERICHOST, NI_NUMERICSERV to prevent name resolution, NI_NAMEREQD to require name). Thread-safe. Returns 0 on success, non-zero gai error code on failure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment