T
T
tex6202018-06-19 12:19:52
C++ / C#
tex620, 2018-06-19 12:19:52

I'm making a port and ip address parser. How to make a timeout?

I'm trying to make a parser in c++ I
wrote this code that puts the socket in non-blocking mode
But the connect function returns a value after 10-30 seconds.
I need to set the timeout to 0.1 second.
How to do it?

void CheckPort(string ip, int port) {
  WSAStartup(MAKEWORD(2, 2), NULL);
  SOCKET sock;
  SOCKADDR_IN Info;
  int nret;
  sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);


  Info.sin_family = AF_INET;
  Info.sin_addr.s_addr = inet_addr(ip.c_str());
  Info.sin_port = htons(port);
  
  u_long nbio = 1;
  ioctlsocket(sock, FIONBIO, &nbio);
  
  timeval tv;  tv.tv_sec = 1;  tv.tv_usec = 0;

  nret = connect(sock, (SOCKADDR *)&Info, sizeof(Info));
  //int result = select(sock, NULL, NULL, NULL, &tv);
  //cout << result << endl;

  if (!nret)
  {
    // connection successful
    cout << ip << " TRUE" << endl;
    output << ip << endl;
  }
  else 
  {
    // connection fail
    cout << ip << " FALSE" << endl;
  }
  closesocket(sock);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2018-06-19
@tex620

https://www.codeproject.com/Tips/168704/How-to-set...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question