-
Notifications
You must be signed in to change notification settings - Fork 2
Networking functions
Cisco edited this page Oct 29, 2025
·
1 revision
int socket(int family, int type, int protocol);
Creates a socket with the specified parameters:-
family: Address family. Common values:- AF_INET (IPv4)
- AF_INET6 (IPv6)
-
type: Socket type. Common values:- SOCK_STREAM (TCP)
- SOCK_DGRAM (UDP)
-
protocol: Protocol to use. Common values:- IPPROTO_TCP (TCP)
- IPPROTO_UDP (UDP)
### Socket Closure
```cpp
int close(int socket);
Closes the specified socket.
Functions to convert between host and network byte order:
short htons(short value); // Host TO Network Short
long htonl(long value); // Host TO Network Long
short ntohs(short value); // Network TO Host Short
long ntohl(long value); // Network TO Host Longint connect(int _socket, const struct sockaddr* server, socklen_t serverlen);-
_socket: Socket to connect. -
server: Structure representing the server to connect to. -
serverlen: Size of the server structure (typically sizeof(server)).
Note
This call is blocking until the connection is established or an error occurs.
Example:
sockaddr_in server;
server.sin_addr.s_addr = inet_addr(const char* ipaddress);
server.sin_family = AF_INET;
server.sin_port = htons(int port);int send(int socket, const void* datas, size_t len, int flags);
int recv(int socket, void* buffer, size_t len, int flags);-
socket: Socket for sending/receiving data. -
datas/buffer: Data to send/receive. -
len: Maximum data size in bytes. -
flags: Options mask (usually 0).
int bind(SOCKET sckt, const struct addr* name, int namelen);Assigns a local address to a socket:
-
sckt: Socket to bind. -
name: Address structure to assign. -
namelen: Size of the structure (use sizeof).
Example:
sockaddr_in addr;
addr.sin_addr.s_addr = INADDR_ANY; // Accept connections from any source
addr.sin_port = htons(port); // Convert port to network byte order
addr.sin_family = AF_INET; // TCP socketint listen(SOCKET sckt, int backlog);-
sckt: Server socket to listen on. -
backlog: Maximum number of pending connections. UseSOMAXCONNfor system default.
SOCKET accept(SOCKET sckt, struct sockaddr* addr, int* addrlen);Accepts an incoming connection:
-
sckt: Server socket waiting for connections. -
addr: Will store the client's address. -
addrlen: Size of the addr structure.
const char* inet_ntop(int family, const void* src, char* dst, socklen_t size);Converts a binary IP address (IPv4/IPv6) to a human-readable string:
-
family: Address family (AF_INET or AF_INET6). -
src: Pointer to the binary address. -
dst: Buffer to store the readable address. -
size: Maximum buffer size.
#include <poll.h>
int poll(struct pollfd *fds, nfds_t nfds, int timeout);Monitors multiple file descriptors (sockets, files, etc.) for readiness (read/write/error) without blocking. pollfd Structure:
struct pollfd {
int fd; // File descriptor to monitor
short events; // Events to monitor (INPUT)
short revents; // Events that occurred (OUTPUT)
};