setsockopt SO_RCVTIMEO for udp::socket in boost::asio
Hello. I tried a simple program with clear sockets: #include
#include #include #include #include <cstring> #include #include <iostream> using namespace std;
/* * */ int main(int argc, char** argv) { if (argc < 2) { cout << "Few parameters" << endl; return 1; }
unsigned int taddr = inet_addr(argv[1]); if(INADDR_NONE == taddr) { cout << "wrong address" << endl; return 1;
}
int sock = socket(AF_INET, SOCK_DGRAM, 0); if( sock < 0 ) { cout << "socket error" << endl; return 1; }
sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET;
unsigned short port = 3334; sin.sin_port = htons(port);
sin.sin_addr.s_addr = taddr; int ret = connect( sock, reinterpret_cast
(&sin), sizeof(sin) ); if ( ret < 0 ) { cout << "connect error" << endl; return 1; } timeval tv; memset( &tv, 0, sizeof(tv) ); tv.tv_sec = 5;
ret = setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv) ); if( ret < 0 ) { cout << "sockopt error" << endl; return 1; }
char hello[] = "hello"; send(sock, hello, sizeof(hello), 0);
char msg[256]; cout << "Recived "<< recv(sock, msg, sizeof(msg), 0) << endl;
close(sock);
return (EXIT_SUCCESS); }
This program just send buffer via connected udp socket and then wait for response. Recv may block only for 5 seconds. All work fine. When I try to make same with boost.asio recieve method does not return if there is no response. I use boost 1.37/
#include
#include <iostream> #include <vector> using boost::asio::ip::udp; using namespace std; int main() { try { boost::asio::io_service serv; udp::socket s( serv, udp::endpoint( udp::v4(), 3333 ) );
udp::resolver::query query(udp::v4(), "127.0.0.1", "3334"); udp::resolver resolver(serv); udp::resolver::iterator iterator = resolver.resolve(query); s.connect(*iterator); int sock = s.native(); cout << sock << endl; timeval tv; memset( &tv, 0, sizeof(tv) ); tv.tv_sec = 5; cout << setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv) ) << endl;
string h("hello"); s.send(boost::asio::buffer(h)); vector<char> v(12); cout << s.receive(boost::asio::buffer(v)) << endl; cout << v.size() << endl; } catch(boost::system::system_error &err) { cout << err.what() << endl; } } I tested both programs with nc -lu 3334 ooh! I use Linux.
participants (1)
-
Евгений Шубин