Advertisement
Guest User

Untitled

a guest
May 29th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. void connect_w_to(void) {
  2. int res, valopt;
  3. struct sockaddr_in addr;
  4. long arg;
  5. fd_set myset;
  6. struct timeval tv;
  7. socklen_t lon;
  8.  
  9. // Create socket
  10. soc = socket(AF_INET, SOCK_STREAM, 0);
  11.  
  12. // Set non-blocking
  13. arg = fcntl(soc, F_GETFL, NULL);
  14. arg |= O_NONBLOCK;
  15. fcntl(soc, F_SETFL, arg);
  16.  
  17. // Trying to connect with timeout
  18. addr.sin_family = AF_INET;
  19. addr.sin_port = htons(2000);
  20. addr.sin_addr.s_addr = inet_addr("192.168.0.1");
  21. res = connect(soc, (struct sockaddr *)&addr, sizeof(addr));
  22.  
  23. if (res < 0) {
  24. if (errno == EINPROGRESS) {
  25. tv.tv_sec = 15;
  26. tv.tv_usec = 0;
  27. FD_ZERO(&myset);
  28. FD_SET(soc, &myset);
  29. if (select(soc+1, NULL, &myset, NULL, &tv) > 0) {
  30. lon = sizeof(int);
  31. getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon);
  32. if (valopt) {
  33. fprintf(stderr, "Error in connection() %d - %s\n", valopt, strerror(valopt));
  34. exit(0);
  35. }
  36. }
  37. else {
  38. fprintf(stderr, "Timeout or error() %d - %s\n", valopt, strerror(valopt));
  39. exit(0);
  40. }
  41. }
  42. else {
  43. fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno));
  44. exit(0);
  45. }
  46. }
  47. // Set to blocking mode again...
  48. arg = fcntl(soc, F_GETFL, NULL);
  49. arg &= (~O_NONBLOCK);
  50. fcntl(soc, F_SETFL, arg);
  51. // I hope that is all
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement