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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?