sockets - Setting a timeout when using connect() in C++ -


I'm using Sekets on Linux to connect to a server, but it does not seem like a Timeout value is the easiest / best method to give it for a few seconds time, I will post the code I have in, and to include, the blocked call ():

 Using  namespace std; Int main (int argc, char * argv []) {// command line argument string uri_string = "interpretation"; If (argc! = 2) {cerr & lt; & Lt; "Use:" & lt; & Lt; Argv [0]; Serie Lieutenant; & Lt; "& Lt; URI & gt;" & Lt; & Lt; Endl; Return 1; } And {uri_string = argv [1]; } // Create a URI object and parse it URI_STRING URI * YURY = URI: Pars (Yuri_String); If (Yuri == tap) {cerr & lt; & Lt; "Error: URI can not be parsed." & Lt; & Lt; Endl; Return 2; } // Check the specified port number, if you do not use a port 80 unsigned ports = 80; If (uri-> Is_port_defined ()) {port = uri- & gt; Gate_port (); } // Create a TCP socket and connect to the server int tcp_sock = socket (AF_INET, SOCK_STREAM, 0); If (tcp_sock & lt; 0) {cerr & lt; & Lt; "Unable to create TCP socket." & Lt; & Lt; Endl; Return 3; } Sockaddr_in Server; Socklen_t slen = sizeof (server); Server.can_family = AF_INET; Server.sin_port = htons (port); Cout & lt; & Lt; "Solution" & lt; & Lt; Yuri- & gt; Get_host () & lt; & Lt; "..."; Hostname * hostp = gethostbyname (Yuri-> Get_host () .c_str ()); Memcpy (& server.cn_addr, hostp- & gt; H_ADD, hostP-> H_Length); Struct in_addr ** pptr; Pptr = (struct in_addr **) hostp-> H_addr_list; String ip_addr = ""; While (* pptr! = NULL) {ip_addr + = inet_ntoa (** (PPTR ++)); } Cout & lt; & Lt; Ip_addr & lt; & Lt; Endl; Cout & lt; & Lt; "Connect to" & lt; & Lt; Yuri- & gt; Get_host () & lt; & Lt; "|" & Lt; & Lt; Ip_addr & lt; & Lt; "|:"; Cout & lt; & Lt; Harbor & lt; & Lt; "..."; If (connected (TCP_sock, (Socadar *) and server, Slane) <0] {cerr & lt; & Lt; "Unable to connect to server via TCP." & Lt; & Lt; Endl; Off (TCP_sock); Return 4; } Cout & lt; & Lt; "Linked." & Lt; & Lt; Endl; // Rest of code}  

Make the socket a non-blocking socket and then the accounting Use the selection () or the choice () with the timeout value to check for if the selection () returns with an expired time, then you were not connected in time, and you can close the socket and the connection Can cope with the failure. If it is done with completion, then everything is fine and you can move forward.


Comments

Popular posts from this blog

asp.net - Javascript/DOM Why is does my form not support submit()? -

sockets - Delphi: TTcpServer, connection reset when reading -

javascript - Classic ASP "ExecuteGlobal" statement acting differently on two servers -