Linux C Socket with timeout
Example
#include <sys/socket.h> #include <sys/time.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <netdb.h> char uri[500]; char request[MAX_SOCKET]; char *cur_p; struct hostent *server; struct sockaddr_in serveraddr; int port = 80; struct timeval Timeout; Timeout.tv_sec = 2; Timeout.tv_usec = 0; int err; fd_set Read, Write, Err; int i; int tcpSocket = socket(AF_INET, SOCK_STREAM,IPPROTO_TCP); if (tcpSocket < 0) { return 1; } FD_ZERO(&Read); FD_ZERO(&Write); FD_ZERO(&Err); FD_SET(tcpSocket, &Read); FD_SET(tcpSocket, &Write); FD_SET(tcpSocket, &Err); /* Resolve the IP */ server = gethostbyname("www.luniel.com"); if (server == NULL) { return 1; } bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = server->h_addrtype; //AF_INET or AF_INET6 bcopy((char *)server->h_addr, (char *)&serveraddr.sin_addr.s_addr, server->h_length); serveraddr.sin_port = htons(port); //set the socket in non-blocking unsigned long iMode = 1; int iResult = ioctl(tcpSocket, FIONBIO, &iMode); if (iResult != 0) { return 1; } if (connect(tcpSocket, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) != 0) { err = errno; if (err != EINPROGRESS ){ return 1; } } // restart the socket mode iMode = 0; iResult = ioctl(tcpSocket, FIONBIO, &iMode); if (iResult != 0) { return 1; } /* Set timeouts to send and receive data */ if (setsockopt (tcpSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&Timeout,sizeof(Timeout)) < 0) { return 1; } if (setsockopt (tcpSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&Timeout,sizeof(Timeout)) < 0) { return 1; } // Check if socket is ready, and if not timeout after 2 seconds int n; n=select(tcpSocket+1,&Read,&Write,NULL,&Timeout); if ( n <= 0) { return 1; } bzero(request, MAX_SOCKET); sprintf(request, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", "/index.html, "www.luniel.com"); if (send(tcpSocket, request, strlen(request), 0) < 0) { return 1; } bzero(request, MAX_SOCKET); recv(tcpSocket, request, MAX_SOCKET-1, 0);
References
- sending an http GET request in C
- How to set socket timeout in C when making multiple connections?
- non-blocking socket with a timeout
- How to set a socket connection timeout
Daniel Simao (talk) 10:08, 15 October 2018 (EDT)