How do I set socket options and timeouts on Linux in C++?

In Linux, you can set socket options and timeouts using the setsockopt() function. This allows you to control various aspects of the socket behavior, including timeouts for send and receive operations. Below is an example illustrating how to do this in C++.

#include <iostream> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <fcntl.h> #include <cstring> #include <unistd.h> int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { std::cerr << "Error opening socket" << std::endl; return 1; } int timeout = 5; // Timeout in seconds setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(timeout)); setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(8080); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { std::cerr << "Error on binding" << std::endl; close(sockfd); return 1; } listen(sockfd, 5); std::cout << "Listening on port 8080..." << std::endl; close(sockfd); return 0; }

C++ socket options timeouts setsockopt Linux programming network programming