TCP
TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain a network conversation via which application programs can exchange data. TCP is a transport layer protocol that provides a reliable, stream-oriented connection between two computers.
Server
Create a Socket
socket_ = socket(AF_INET, SOCK_STREAM, 0);
if (socket_ < 0) {
// Failed to create Socket
}
Set the socket to non-blocking mode
int flags = fcntl(socket_, F_GETFL, 0);
if (flags < 0) {
// Failed to get flags
}
if (fcntl(socket_, F_SETFL, flags | O_NONBLOCK) < 0) {
// Failed to set socket to non-blocking
}
Bind the socket to a local address
unsigned short port = 1234;
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
if (bind(socket_, (sockaddr*)&addr, sizeof(addr)) < 0) {
// Failed to bind.
}
Start listening for incoming connections.
if (listen(socket_, backlog_size) < 0) {
// Failed to listen.
}
Set Accept Connection Timeout
timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
if (setsockopt(socket_, SOL_SOCKET, SO_ACCEPTCONN, &tv, sizeof(tv)) < 0) {
// Failed to set connection timeout.
}
Accept a Client
sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
int client_socket = accept(socket_, (sockaddr*)&addr, &addr_len);
if (client_socket < 0) {
// The accept() call may fail with EAGAIN if it is called in non-blocking
// mode and there are no pending connections. In this case, just return
// empty optional.
if (errno != EAGAIN && errno != EINTR) {
// Failed to accept client.
}
}
Set the client socket to non-blocking mode
int flags = fcntl(client_socket, F_GETFL, 0);
if (flags < 0) {
// Failed to get flags.
}
if (fcntl(client_socket, F_SETFL, flags | O_NONBLOCK) < 0) {
// Failed to set socket to non-blocking.
}
Get Client's IP
sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
if (getpeername(socket_, (sockaddr*)&addr, &addr_len) < 0) {
// Failed to get peer name
}
// Convert the IP address to a string
char client_ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &addr.sin_addr, client_ip, INET_ADDRSTRLEN);
auto ip = std::string(client_ip);