-
<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 tostdout. Returns number of characters written or negative on error.int fprintf(FILE *stream, const char *format, ...): Print formatted string output to the specifiedstream. 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 stringstr, writing at mostsizebytes (including null terminator). Safer alternative tosprintf. Returns number of characters that would have been written (excluding null) ifsizewas large enough, or negative on error.int sprintf(char *str, const char *format, ...): UNSAFE! Print formatted output to the character stringstr. No bounds checking! Can easily cause buffer overflows. Returns number of characters written (excluding null).int scanf(const char *format, ...): Read formatted input fromstdin. Returns number of items successfully assigned orEOF.int fscanf(FILE *stream, const char *format, ...): Read formatted input from the specifiedstream. Returns number of items successfully assigned orEOF.int sscanf(const char *str, const char *format, ...): Read formatted input from the character stringstr. Returns number of items successfully assigned orEOF.FILE *fopen(const char *pathname, const char *mode): Open the file specified bypathnamewith the givenmode(e.g., "r", "w", "a", "rb", "wb", "ab", "+ variants"). ReturnsFILE *stream orNULLon error (checkerrno).int fclose(FILE *stream): Close the specified filestream, flushing any buffered data. Returns 0 on success,EOFon error.size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream): Readnmembitems, eachsizebytes long, fromstreaminto the bufferptr. Used for binary input. Returns number of items successfully read (may be less thannmembat EOF or error).size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream): Writenmembitems, eachsizebytes long, from bufferptrtostream. Used for binary output. Returns number of items successfully written (may be less thannmembon error).char *fgets(char *s, int size, FILE *stream): Read at mostsize-1characters fromstreaminto the buffers. Stops on newline (which is included) or EOF. Null-terminatess. Safer thangets. Returnsson success,NULLon EOF/error.int fputs(const char *s, FILE *stream): Write the null-terminated stringstostream. Does not write the null terminator or add a newline. Returns non-negative on success,EOFon error.int puts(const char *s): Write the null-terminated stringsand a trailing newline tostdout. Returns non-negative on success,EOFon error.int fgetc(FILE *stream): Read the next character fromstreamas anunsigned charcast to anint. Returns the character orEOFon end-of-file or error.int getc(FILE *stream): Similar tofgetc, potentially implemented as a macro (beware side effects in arguments).int getchar(void): Equivalent togetc(stdin). Read next char from standard input.int fputc(int c, FILE *stream): Write the characterc(cast tounsigned char) tostream. Returns the character written orEOFon error.int putc(int c, FILE *stream): Similar tofputc, potentially implemented as a macro.int putchar(int c): Equivalent toputc(c, stdout). Write charcto standard output.int fflush(FILE *stream): Flush the output buffer of thestream. IfstreamisNULL, flush all output streams. Returns 0 on success,EOFon error.int fseek(FILE *stream, long offset, int whence): Set the file position indicator forstream.whenceisSEEK_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 forstream, or -1L on error.void rewind(FILE *stream): Equivalent tofseek(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 forstreamis set. Returns non-zero if EOF, 0 otherwise.int ferror(FILE *stream): Check if the error indicator forstreamis set. Returns non-zero if error, 0 otherwise.void clearerr(FILE *stream): Clear the end-of-file and error indicators forstream.void perror(const char *s): Print the strings, a colon, a space, and the system error message corresponding to the currenterrnovalue tostderr.int remove(const char *pathname): Delete the file specified bypathname. Returns 0 on success, non-zero on error.int rename(const char *oldpath, const char *newpath): Rename/move the fileoldpathtonewpath. Returns 0 on success, non-zero on error.char *gets(char *s): UNSAFE! EXTREMELY DANGEROUS! Reads a line from stdin intoswithout 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) forstream. 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. Usemkstempinstead.FILE *tmpfile(void): Creates and opens a unique temporary binary file ("wb+") that is automatically removed when closed or program terminates. ReturnsFILE*orNULL. Safer thantmpnam.
- Provides core functions for performing input and output operations, primarily using buffered streams (
-
<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): Allocatesizebytes of raw, uninitialized memory block dynamically on the heap; returns pointer to allocated memory orNULLon failure.void free(void *ptr): Deallocate the memory block pointed to byptr(which must have been returned bymalloc,calloc, orrealloc, or beNULL). PassingNULLis safe and does nothing.void *calloc(size_t nmemb, size_t size): Allocate memory for an array ofnmembelements ofsizebytes each, initialize allocated memory to zero; returns pointer orNULLon failure.void *realloc(void *ptr, size_t size): Change the size of the previously allocated memory block atptrtosizebytes. May move the block. Returns new pointer orNULLon failure. IfptrisNULL, equivalent tomalloc(size). Ifsizeis 0, may freeptror return unique pointer (behavior varies, best to usefreeexplicitly).void exit(int status): Terminate the calling process normally. Performs cleanup (flushes stdio, callsatexithandlers) then calls_exit(status).statusis exit code (0 orEXIT_SUCCESSfor success,EXIT_FAILUREor non-zero for failure).void abort(void): Cause abnormal process termination (often by raisingSIGABRT). May not perform standard cleanup.int atexit(void (*func)(void)): Register a functionfuncto be called automatically at normal program termination (exit()or return frommain). Returns 0 on success.long strtol(const char *nptr, char **endptr, int base): Convert the initial part of the stringnptrto along intvalue according to the givenbase(0, 2-36). Stores pointer to first invalid char in*endptr(if notNULL). Robust error checking viaerrnoandendptr.unsigned long strtoul(const char *nptr, char **endptr, int base): Convert the initial part of the stringnptrto anunsigned long int. Similar robustness tostrtol.double strtod(const char *nptr, char **endptr): Convert the initial part of the stringnptrto adouble. Similar robustness. Robust error checking viaerrnoandendptr.int rand(void): Return a pseudo-random integer between 0 andRAND_MAX. Low quality PRNG, not suitable for cryptography or serious simulations.void srand(unsigned int seed): Seed the pseudo-random number generator used byrand()withseed. Often seeded withtime(NULL).void qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Sort an arraybaseofnmembelements each ofsizebytes, using thecomparfunction for comparison.compar(a, b)should return <0 ifa<b, 0 ifa==b, >0 ifa>b.void *bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *)): Perform binary search forkeyin the sorted arraybase. Returns pointer to matching element orNULLif not found.comparfunction same as forqsort.char *getenv(const char *name): Get the value of an environment variablename. Returns pointer to value string (do not modify) orNULLif not found.int system(const char *command): Execute a shellcommand. Returns command's exit status or -1 on error. Warning: Security risks ifcommandstring contains untrusted user input (potential command injection). IfcommandisNULL, returns non-zero if shell is available, 0 otherwise.int abs(int j): Compute absolute value of integerj. (Behavior undefined forINT_MIN).long labs(long j): Compute absolute value of long integerj. (Behavior undefined forLONG_MIN).div_t div(int numerator, int denominator): Compute integer divisionnumerator / denominator. Returnsdiv_tstruct containingquot(quotient) andrem(remainder). Handles signs correctly.ldiv_t ldiv(long numerator, long denominator): Long integer version ofdiv. Returnsldiv_tstruct.int atoi(const char *nptr): UNSAFE (limited)! Convert initial part of stringnptrtoint. No error checking (returns 0 on error, indistinguishable from valid 0). Usestrtolfor robustness.long atol(const char *nptr): UNSAFE (limited)! Convert initial part of stringnptrtolong. No error checking. Usestrtol.double atof(const char *nptr): UNSAFE (limited)! Convert initial part of stringnptrtodouble. Limited error checking. Usestrtodfor robustness.char *mktemp(char *template): UNSAFE! Creates a unique temporary filename based ontemplate(which must end in XXXXXX). Modifiestemplate. Prone to race conditions. Usemkstemp. Removed in POSIX.1-2008.int mkstemp(char *template): (Requires<unistd.h>typically, but closely related tomktemp). Creates and opens a unique temporary file based ontemplate(ending in XXXXXX), modifyingtemplateto the actual filename. Returns file descriptor. Much safer thanmktemp.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 byrand().
-
<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): Copynbytes from memory areasrcto memory areadest. Behavior is undefined ifsrcanddestoverlap. Returnsdest.void *memmove(void *dest, const void *src, size_t n): Copynbytes from memory areasrcto memory areadest. Areas may overlap (handles overlap correctly). Returnsdest.void *memset(void *s, int c, size_t n): Fill the firstnbytes of the memory areaswith the constant bytec(converted tounsigned char). Returnss. Often used to zero memory (e.g.,memset(ptr, 0, size)).int memcmp(const void *s1, const void *s2, size_t n): Compare the firstnbytes of memory areass1ands2. Returns an integer less than, equal to, or greater than zero ifs1is found, respectively, to be less than, to match, or be greater thans2.void *memchr(const void *s, int c, size_t n): Scan the firstnbytes of memory areasfor the first instance of bytec(converted tounsigned char). Returns pointer to the byte orNULLif not found.size_t strlen(const char *s): Calculate the length of the null-terminated strings(excluding the null byte).char *strcpy(char *dest, const char *src): UNSAFE! Copy the null-terminated stringsrctodest(including null terminator). No bounds checking! High risk of buffer overflows. Usestrncpy(carefully) orsnprintf. Returnsdest.char *strncpy(char *dest, const char *src, size_t n): Copy at mostnbytes from stringsrctodest. Warning: Ifstrlen(src) >= n,destwill not be null-terminated. Always ensure null termination manually if needed (e.g.,dest[n-1] = '\0';ifn > 0). Returnsdest.char *strcat(char *dest, const char *src): UNSAFE! Append the null-terminated stringsrcto the end ofdest. No bounds checking ondest! High risk of buffer overflows. Usestrncat. Returnsdest.char *strncat(char *dest, const char *src, size_t n): Append at mostnbytes from stringsrctodest, plus a null terminator. Safer thanstrcat, but requiresdestto have enough space for its original content,nbytes fromsrc, and the null terminator. Always null-terminates (unlikestrncpy). Returnsdest.int strcmp(const char *s1, const char *s2): Compare two null-terminated stringss1ands2lexicographically. Returns <0, 0, or >0.int strncmp(const char *s1, const char *s2, size_t n): Compare at mostnbytes (or until a null terminator) of stringss1ands2. Returns <0, 0, or >0.char *strchr(const char *s, int c): Find the first occurrence of the characterc(converted tochar) in the null-terminated strings. Returns pointer to the character insorNULLif not found.char *strrchr(const char *s, int c): Find the last occurrence of the characterc(converted tochar) in the null-terminated strings. Returns pointer orNULL.char *strstr(const char *haystack, const char *needle): Find the first occurrence of the null-terminated substringneedlewithin the null-terminated stringhaystack. Returns pointer to the beginning of the substring inhaystackorNULL.size_t strspn(const char *s, const char *accept): Calculate the length of the initial segment ofswhich consists only of characters found inaccept.size_t strcspn(const char *s, const char *reject): Calculate the length of the initial segment ofswhich consists only of characters not found inreject.char *strpbrk(const char *s, const char *accept): Find the first character insthat matches any character specified inaccept. Returns pointer to the character orNULL.char *strtok(char *str, const char *delim): UNSAFE (Stateful/Not Reentrant)! Find tokens (substrings separated bydelim) instr. Modifiesstrby inserting null bytes. Passstron first call,NULLon subsequent calls to get next token. Not thread-safe. Usestrtok_r(POSIX) if available. Returns pointer to token orNULL.char *strerror(int errnum): Return a pointer to a string describing the error codeerrnum. The string may be statically allocated and overwritten by subsequent calls (potentially not thread-safe depending on implementation). Usestrerror_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 bysizeofoperator, 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 amemberwithin astructorunionoftype. Result is of typesize_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 avoid*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 forsize_t.
-
<errno.h>(System Error Numbers)- Defines the integer variable
errnoand 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
errnovalue 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).
- Defines the integer variable
-
<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 likeread,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 tocountbytes from file descriptorfdintobuf. Returns bytes read (0 on EOF), or -1 on error (checkerrno).int write(int fd, const void *buf, size_t count): Write up tocountbytes frombufto file descriptorfd. Returns bytes written, or -1 on error (checkerrno).int close(int fd): Close the file descriptorfd. 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 descriptorfd.whenceisSEEK_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 frompathname.argvis the argument list (null-terminated array),envpis the environment (null-terminated array). Does not return on success. Returns -1 on error. The coreexecfunction.int execv(const char *pathname, char *const argv[]): Likeexecve, uses current environment.int execvp(const char *file, char *const argv[]): Likeexecv, but searchesPATHenvironment variable forfileif it doesn't contain a slash. Common variant.int execl(const char *pathname, const char *arg, ... /*, (char *) NULL */): List-based variant ofexec, takes arguments as separateconst char*parameters, terminated byNULL. Uses current environment.int execlp(const char *file, const char *arg, ... /*, (char *) NULL */): List-based variant likeexecl, but searchesPATHlikeexecvp.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.statusis exit code (low 8 bits available to parent viawait). Usually called byexit().unsigned int alarm(unsigned int seconds): Arrange forSIGALRMsignal to be delivered to the process inseconds. Ifsecondsis 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 witherrnoset toEINTR.unsigned int sleep(unsigned int seconds): Suspend execution for the specified number ofseconds, 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 forusecmicroseconds. Usenanosleepinstead. 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 descriptoroldfd, returning the lowest unused non-negative descriptor. Returns new fd or -1.int dup2(int oldfd, int newfd): Duplicateoldfdtonewfd, closingnewfdfirst if necessary. Ifoldfd==newfd, does nothing. Returnsnewfdor -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 topath. Returns 0 on success, -1 on error.char *getcwd(char *buf, size_t size): Copy the absolute pathname of the current working directory tobuf(up tosizebytes). IfbufisNULL, allocates buffer (needsfree). ReturnsbuforNULLon error.char *getwd(char *buf): UNSAFE! DEPRECATED! Get current working directory intobuf. Cannot specify buffer size, potential overflow. Usegetcwd.int chown(const char *pathname, uid_t owner, gid_t group): Change the owner and group of a file specified bypathname. Use -1 for owner/group to leave unchanged. Returns 0 on success, -1 on error. (lchownchanges symlink itself,fchownuses fd).int access(const char *pathname, int mode): Check user's permissions for a file.modeis bitwise OR ofR_OK,W_OK,X_OK(test permissions), orF_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 descriptorfdrefers to a terminal. Returns 1 if it is, 0 otherwise (settingerrnoif error occurs).int link(const char *oldpath, const char *newpath): Create a new hard linknewpathfor the existing fileoldpath. Returns 0 on success, -1 on error.int symlink(const char *target, const char *linkpath): Create a symbolic link namedlinkpathcontaining the stringtarget. Returns 0 on success, -1 on error.ssize_t readlink(const char *pathname, char *buf, size_t bufsiz): Read the value of a symbolic linkpathnameintobuf(up tobufsizbytes). Does not null-terminatebuf. 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).flagsis 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.). Optionalmodeargument (e.g.,0644) is required only whenO_CREATis specified, sets initial permissions (modified by umask). Returns fd or -1 on error.int creat(const char *pathname, mode_t mode): DEPRECATED. Equivalent toopen(pathname, O_WRONLY|O_CREAT|O_TRUNC, mode). Useopendirectly.int fcntl(int fd, int cmd, ... /* arg */): Perform various operations (cmd) on file descriptorfd. Common commands:F_DUPFD: Duplicate fd (likedup, but to lowest >=arg).F_GETFD/F_SETFD: Get/set fd flags (e.g.,FD_CLOEXEC).argis int.F_GETFL/F_SETFL: Get/set file status flags (e.g.,O_APPEND,O_NONBLOCK).argis int.F_GETLK/F_SETLK/F_SETLKW: Get/Set/Set-and-wait for file locks.argisstruct flock *.
- Common
open/fcntlflags: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 withO_CREAT, ensuresopenfails 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 withEAGAIN/EWOULDBLOCK).O_CLOEXEC: Set the close-on-exec flag for the new file descriptor (atomically). Prevents fd leakage acrossexec.
FD_CLOEXEC: File descriptor flag (forF_GETFD/F_SETFD) indicating fd should be closed automatically uponexec.
- Defines functions and constants for manipulating file descriptors, such as opening files (
-
<sys/stat.h>(File Status and Information)- Defines the
statstructure 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 forpathname(follows symbolic links) and store it instatbuf. Returns 0 on success, -1 on error.int fstat(int fd, struct stat *statbuf): Get file status for the open file descriptorfd. Returns 0 on success, -1 on error.int lstat(const char *pathname, struct stat *statbuf): Get file status forpathname. Ifpathnameis 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 namedpathnamewith specified initialmode(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 filepathname. Returns 0 on success, -1 on error. (fchmodoperates on an fd).mode_t umask(mode_t mask): Set the process's file mode creation mask and return the previous mask. Bits set inmaskare cleared from the mode specified inopenormkdir.- File type macros (for testing
st_modefield):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? (Uselstatto get mode for link itself).S_ISSOCK(m): Is it a socket?
- Permission bits (for
st_modefield andmodearguments toopen/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.
- Defines the
-
<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 bylseek).mode_t: Integer type for file modes/permissions (used bystat,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>.
- Defines various basic data types used in system calls and other POSIX headers. Often included implicitly by other headers like
-
<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 withsigactionto 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 signalsignum.actspecifies 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 signalsignum.handlercan beSIG_DFL(default),SIG_IGN(ignore), or a function pointer. Semantics vary across systems (especially regarding handler re-installation). Usesigactioninstead for reliable behavior. Returns previous handler orSIG_ERRon error.int kill(pid_t pid, int sig): Send signalsigto processpid. Specialpidvalues: >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 signalsigto the calling process or thread. Equivalent tokill(getpid(), sig). Returns 0 on success, non-zero on error.int sigemptyset(sigset_t *set): Initialize the signal setsetto be empty (exclude all signals). Returns 0 on success, -1 on error.int sigfillset(sigset_t *set): Initialize the signal setsetto be full (include all signals). Returns 0 on success, -1 on error.int sigaddset(sigset_t *set, int signum): Add signalsignumto the signal setset. Returns 0 on success, -1 on error.int sigdelset(sigset_t *set, int signum): Remove signalsignumfrom the signal setset. Returns 0 on success, -1 on error.int sigismember(const sigset_t *set, int signum): Test ifsignumis a member of the signal setset. 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(addsetto mask),SIG_UNBLOCK(removesetfrom mask),SIG_SETMASK(set mask toset). Ifoldsetis 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 inset. Returns 0 on success, -1 on error.int sigsuspend(const sigset_t *mask): Atomically set the signal mask tomaskand suspend the process until a signal is caught (whose action isn't ignore) or terminates the process. Restores original mask on return. Returns -1 witherrnoEINTR.- Handler Macros:
SIG_DFL: Specifies the default action for the signal.SIG_IGN: Specifies that the signal should be ignored.SIG_ERR: Return value fromsignalindicating 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., fromabort()).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 fromalarm().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. Ifwstatusis notNULL, stores status information there. Returns PID of the child whose state changed, or -1 on error (e.g., no children). Equivalent towaitpid(-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 PIDpid.pid == -1: Wait for any child process (likewait).pid == 0: Wait for any child in the calling process's process group.pid < -1: Wait for any child in the process groupabs(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
WNOHANGand no change), or -1 on error.
- Wait status analysis macros (used with the
wstatusvalue):WIFEXITED(wstatus): Returns true (non-zero) if the child terminated normally (viaexit()orreturnfrommain).WEXITSTATUS(wstatus): IfWIFEXITEDis 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): IfWIFSIGNALEDis true, returns the number of the signal that terminated the child.WIFSTOPPED(wstatus): Returns true if the child was stopped by a signal (requiresWUNTRACEDorWCONTINUEDinwaitpid).WSTOPSIG(wstatus): IfWIFSTOPPEDis true, returns the number of the signal that stopped the child.WIFCONTINUED(wstatus): Returns true if the child was resumed bySIGCONT(requiresWCONTINUED).
-
<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 astime_t(seconds since the Epoch). Iftlocis notNULL, the value is also stored there. Returns current time or(time_t)-1on error.struct tm *localtime(const time_t *timep): Converttime_tvaluetimepinto broken-down timestruct tmexpressed in the system's local timezone. Warning: Returns pointer to a static internal buffer, which may be overwritten by subsequent calls tolocaltimeorgmtime. Not thread-safe. Uselocaltime_r(POSIX) for thread-safety.struct tm *gmtime(const time_t *timep): Converttime_tvaluetimepinto broken-down timestruct tmexpressed in Coordinated Universal Time (UTC, often called GMT). Warning: Returns pointer to static data, not thread-safe. Usegmtime_r(POSIX).time_t mktime(struct tm *tm): Convert broken-down local timestruct tm(fieldstm_wdayandtm_ydayare ignored, others normalized) intotime_tcalendar time value. Returnstime_tvalue or(time_t)-1if it cannot be represented. Modifies thetmstruct, filling intm_wdayandtm_yday.size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *tm): Format the broken-down timetminto the strings(up tomaxsizebytes, including null) according toformatspecifiers (e.g.,%Yyear,%mmonth,%dday,%Hhour,%Mmin,%Ssec,%Ztimezone name). Returns number of bytes written (excluding null) or 0 ifmaxsizewas too small.char *asctime(const struct tm *tm): Convertstruct tminto a standard C string format (e.g., "Wed Jun 30 21:49:08 1993\n"). Warning: Returns pointer to static data, not thread-safe. Usestrftime.char *ctime(const time_t *timep): Converttime_tinto a standard C string format (likeasctime). Equivalent toasctime(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 twotime_tvalues (time1-time0), returned as adouble.clock_t clock(void): Return the processor time consumed by the program since invocation, measured inclock_tunits. Divide byCLOCKS_PER_SECto get seconds. May wrap. Quality/granularity varies.CLOCKS_PER_SEC: Macro defining the number ofclock_tticks 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 forgettimeofday. (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 withgettimeofdayfor timezone information. Do not use; passNULLfor thetzargument.int gettimeofday(struct timeval *tv, struct timezone *tz): Get the current time as seconds and microseconds since the Epoch.tzargument is obsolete and should beNULL. Returns 0 on success, -1 on error. Still very common, though POSIX favorsclock_gettimefrom<time.h>(if available withCLOCK_REALTIME).
- Provides structures and functions for more precise time measurements (microseconds). Often included by
-
<math.h>(Mathematical Functions)- Provides common mathematical functions, primarily operating on
doublefloating-point numbers. double sqrt(double x): Compute the non-negative square root ofx(x >= 0).double pow(double base, double exp): Computebaseraised to the powerexp(base^exp). Handles various edge cases (0, infinity, NaN).double fabs(double x): Compute the absolute value of floating-point numberx. (fabsfforfloat,fabslforlong double).double fmod(double x, double y): Compute floating-point remainder ofx/y. Result has the same sign asx.double exp(double x): Compute e (Euler's number, ~2.718) raised to the powerx(e^x).double log(double x): Compute the natural logarithm (base e) ofx(x > 0).double log10(double x): Compute the base-10 logarithm ofx(x > 0).double sin(double x),double cos(double x),double tan(double x): Compute sine, cosine, tangent ofx(wherexis in radians).double asin(double x),double acos(double x),double atan(double x): Compute arc sine (xin [-1,1]), arc cosine (xin [-1,1]), arc tangent ofx. Results are in radians.double atan2(double y, double x): Compute arc tangent ofy/x, using the signs ofxandyto determine the correct quadrant for the result (in radians, range [-pi, pi]).double ceil(double x): Roundxupward to the nearest integer value (returned asdouble). "Ceiling".double floor(double x): Roundxdownward to the nearest integer value (returned asdouble). "Floor".double round(double x): (C99) Roundxto the nearest integer value (returned asdouble), rounding halfway cases away from zero.double trunc(double x): (C99) Roundxtoward zero to the nearest integer value (returned asdouble).double hypot(double x, double y): (C99) Computesqrt(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 (floattype).NAN: (C99) Macro representing a "Not a Number" floating-point value (floattype).fpclassify(x),isfinite(x),isinf(x),isnan(x),isnormal(x),signbit(x): (C99) Macros for classifying floating-point values.
- Provides common mathematical functions, primarily operating on
-
<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
intargument but typically operate on values representable asunsigned charorEOF. int isalnum(int c): Check ifcis alphanumeric (isalphaorisdigit).int isalpha(int c): Check ifcis an alphabetic character (isupperorislower).int iscntrl(int c): Check ifcis a control character.int isdigit(int c): Check ifcis a decimal digit ('0'-'9').int isgraph(int c): Check ifcis any printable character except space.int islower(int c): Check ifcis a lowercase letter.int isprint(int c): Check ifcis a printable character (including space).int ispunct(int c): Check ifcis a punctuation character (printable, not space orisalnum).int isspace(int c): Check ifcis whitespace (space ' ', form feed '\f', newline '\n', carriage return '\r', horizontal tab '\t', vertical tab '\v').int isupper(int c): Check ifcis an uppercase letter.int isxdigit(int c): Check ifcis a hexadecimal digit ('0'-'9', 'a'-'f', 'A'-'F').int tolower(int c): Convert uppercase lettercto lowercase. Returnscunchanged if not uppercase.int toupper(int c): Convert lowercase lettercto uppercase. Returnscunchanged if not lowercase.
- Provides functions for testing characters against various classifications (digit, letter, whitespace, etc.) and for converting between uppercase and lowercase. Functions take
-
<stdbool.h>(Boolean Type and Values - C99 onwards)- Defines a boolean type and constants
trueandfalsefor improved code clarity. Often implemented via macros that expand to integer types/values. bool: Macro expanding to the boolean type (_Booltypically).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.
- Defines a boolean type and constants
-
<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 achar.CHAR_MIN,CHAR_MAX: Minimum/Maximum value forchar.SCHAR_MIN,SCHAR_MAX: Minimum/Maximum value forsigned char.UCHAR_MAX: Maximum value forunsigned char.SHRT_MIN,SHRT_MAX: Minimum/Maximum value forshort int.USHRT_MAX: Maximum value forunsigned short int.INT_MIN,INT_MAX: Minimum/Maximum value forint.UINT_MAX: Maximum value forunsigned int.LONG_MIN,LONG_MAX: Minimum/Maximum value forlong int.ULONG_MAX: Maximum value forunsigned long int.LLONG_MIN,LLONG_MAX: (C99) Minimum/Maximum value forlong long int.ULLONG_MAX: (C99) Maximum value forunsigned long long int.
- Defines macros specifying the limits (minimum and maximum values) for the standard fundamental integer types like
-
<assert.h>(Debugging Assertions)- Provides the
assertmacro, used for inserting run-time sanity checks during development. void assert(scalar expression): If the macroNDEBUGis not defined at the point of inclusion of<assert.h>,assertevaluatesexpression. Ifexpressionis false (evaluates to 0),assertprints an error message (including the expression text, file name, and line number) tostderrand then callsabort(). IfNDEBUGis defined, theassertmacro expands to nothing((void)0), effectively disabling the check for release builds.
- Provides the
-
<stdarg.h>(Variable Argument Lists)- Provides macros for implementing functions that accept a variable number of arguments (like
printforscanf). va_list: Type suitable for holding information needed byva_start,va_arg, andva_end.void va_start(va_list ap, last): Initializesapfor use byva_argandva_end.lastmust be the name of the last fixed parameter before the variable arguments (...). Must be called before firstva_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.apmust have been initialized byva_start.typeis the expected type of the next argument. Behavior undefined if no next argument or iftypeis incompatible. Modifiesap.void va_end(va_list ap): Performs necessary cleanup forapafter all arguments have been processed. Must be called before the function returns ifva_startwas called.void va_copy(va_list dest, va_list src): (C99) Creates a copydestof the current variable argument list statesrc. Useful if the list needs to be scanned more than once.destmust also be passed tova_end.
- Provides macros for implementing functions that accept a variable number of arguments (like
-
<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_INETfor IPv4,AF_INET6for IPv6,AF_UNIXfor local).type: Communication semantics (e.g.,SOCK_STREAMfor reliable stream/TCP,SOCK_DGRAMfor datagram/UDP,SOCK_RAWfor raw network protocol access). AddSOCK_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 socketsockfd. Typically used on the server side beforelistenor for specific client-side source address/port. Returns 0 on success, -1 on error.int listen(int sockfd, int backlog): Marksockfd(which must be of typeSOCK_STREAMorSOCK_SEQPACKET) as a passive socket that will be used to accept incoming connection requests.backlogsuggests 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 socketsockfd, extract the first connection request on the queue, create a new connected socket for this specific connection, and return its file descriptor. Ifaddrandaddrlenare non-NULL, they are filled with the address of the connecting peer (client).addrlenis value-result: initialize it tosizeof(*addr)before the call. Blocks by default until a connection arrives. Returns new socket fd or -1 on error. (Linux extension:accept4adds flags likeSOCK_NONBLOCK,SOCK_CLOEXEC).int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen): Initiate a connection on socketsockfd(client side) to the server address specified byaddr. 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): Sendlenbytes frombufon a connected socketsockfd.flagsmodify behavior (e.g.,MSG_NOSIGNALon Linux preventsSIGPIPE). Returns number of bytes sent (can be less thanlen) or -1 on error.ssize_t recv(int sockfd, void *buf, size_t len, int flags): Receive up tolenbytes intobuffrom a connected socketsockfd.flagsmodify behavior (e.g.,MSG_PEEKlooks 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): Sendlenbytes frombufon socketsockfd(can be connected or unconnected, typically UDP) to the specific destination addressdest_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 tolenbytes intobuffrom socketsockfd. Ifsrc_addrandaddrlenare non-NULL, they are filled with the address of the sender.addrlenis 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 socketsockfd.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 socketsockfd.levelindicates protocol level (e.g.,SOL_SOCKET,IPPROTO_TCP).optnameis the option name (e.g.,SO_REUSEADDR,SO_ERROR,TCP_NODELAY). Value stored inoptval, length inoptlen(value-result). Returns 0 or -1.int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen): Set options for socketsockfd. Parameters similar togetsockopt. Returns 0 or -1.struct sockaddr: Generic socket address structure (base type, containssa_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 foracceptorrecvfrom. Containsss_family.socklen_t: Unsigned integer type used for socket address structure lengths (passed tobind,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 (
optnameforSOL_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 tosockfd.int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen): Get the remote address/port connected tosockfd.
-
<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
socketprotocolfield orgetprotobyname):IPPROTO_IP,IPPROTO_TCP,IPPROTO_UDP,IPPROTO_IPV6,IPPROTO_ICMP. INADDR_ANY: IPv4 wildcard address (0.0.0.0) for binding (usehtonl(INADDR_ANY)).INADDR_LOOPBACK: IPv4 loopback address (127.0.0.1) (usehtonl(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 stringsrc(e.g., "192.0.2.1" or "2001:db8::1") in presentation format to binary network address format (stored indst, which should be astruct in_addr *forAF_INETorstruct in6_addr *forAF_INET6).afspecifies the address family. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns 1 on success, 0 ifsrcis not a valid address string foraf, -1 on error (errnoset).const char *inet_ntop(int af, const void *src, char *dst, socklen_t size): Convert binary network addresssrc(struct in_addr *orstruct in6_addr *) to presentation format stringdst.sizeis the size of thedstbuffer. Modern, preferred, thread-safe, handles IPv4/IPv6. Returns pointer todston success,NULLon error (errnoset, e.g.,ENOSPCifsizetoo small). UseINET_ADDRSTRLENandINET6_ADDRSTRLEN(defined in<netinet/in.h>) for adequate buffer sizes.in_addr_t inet_addr(const char *cp): DEPRECATED/UNSAFE! Convert IPv4 address stringcp(dotted-decimal) to binaryuint32_tin network byte order. ReturnsINADDR_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. Useinet_pton.char *inet_ntoa(struct in_addr in): DEPRECATED/UNSAFE! Convert binary IPv4 addressin(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. Useinet_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 bygetaddrinfoto 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 ofai_addr.struct sockaddr *ai_addr: Pointer to socket address structure.char *ai_canonname: Pointer to canonical hostname (ifAI_CANONNAMErequested).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 moreaddrinfostructures, returned as a linked list viares.hintsprovides 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 tosocket,bind,connect. Returns 0 on success, non-zero error code (usegai_strerrorto convert to string) on failure.void freeaddrinfo(struct addrinfo *res): Free the linked list ofaddrinfostructures allocated and returned bygetaddrinfo. Must be called to prevent memory leaks.const char *gai_strerror(int errcode): Convert the error code returned bygetaddrinfointo a human-readable string.struct hostent *gethostbyname(const char *name): DEPRECATED. Look up hostname(hostname or IPv4 dotted-decimal). Returns pointer to statichostentstructure containing addresses, aliases, etc. Only reliably handles IPv4. Not thread-safe. Usegetaddrinfo.struct hostent *gethostbyaddr(const void *addr, socklen_t len, int type): DEPRECATED. Reverse lookup: find hostname for binary addressaddr. OnlyAF_INET(type) usually supported. Returns pointer to statichostent. Not thread-safe. Usegetnameinfoorgetaddrinfo.struct servent *getservbyname(const char *name, const char *proto): DEPRECATED. Look up servicename(e.g., "http") for a given protocol (proto, e.g., "tcp"). Returns pointer to staticserventstructure containing port number. Not thread-safe. Usegetaddrinfo.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 addresssaback into hostname (stored inhost) and service name (stored inserv).flagscontrol lookup behavior (e.g.,NI_NUMERICHOST,NI_NUMERICSERVto prevent name resolution,NI_NAMEREQDto require name). Thread-safe. Returns 0 on success, non-zerogaierror code on failure.
- Provides functions for translating between hostnames/service names and network addresses/port numbers, querying the network databases (like
Created
March 29, 2025 20:31
-
-
Save qpwo/9f577f1ca74f7176687f9e6130bab535 to your computer and use it in GitHub Desktop.
top 250 c standard library things
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment