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

Setting socket options and timeouts in C++ on macOS can be accomplished using the `setsockopt` function for configuring options and `select` or `poll` for managing timeouts. Below is an example demonstrating how to configure socket options and implement a timeout for a socket connection.

#include #include #include #include #include int main() { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { std::cerr << "Error creating socket." << std::endl; return -1; } // Set socket options int opt = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { std::cerr << "Error setting socket options." << std::endl; close(sockfd); return -1; } // Setting a timeout for receive operations struct timeval timeout; timeout.tv_sec = 5; // timeout in seconds timeout.tv_usec = 0; // timeout in microseconds if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout)) < 0) { std::cerr << "Error setting receive timeout." << std::endl; close(sockfd); return -1; } // Connect to a server struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(8080); // Port number // Assuming the server IP address is set correctly inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr); if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { std::cerr << "Error connecting to server." << std::endl; close(sockfd); return -1; } // Your communication logic here close(sockfd); return 0; }

socket options macOS C++ socket timeouts setsockopt example C++ networking