We help IT Professionals succeed at work.

How to detect socket states, such as ESTABLISHED,CLOSED,etc?

lutfcn asked
Medium Priority
Last Modified: 2013-12-03
Can u tell me the windows APIs for the function?
Watch Question

try "netstat"
hope helps...
you might try using the select function.

#include "winsock2.h"
#include "stdio.h"
#include "conio.h"

void TellSockState(SOCKET s)
     printf("retrieving socket state...\n");
     FD_SET fdr, fdw, fde;
     fde.fd_count = fdw.fd_count = fdr.fd_count = 1;
     fde.fd_array[0] = fdw.fd_array[0] = fdr.fd_array[0] = s;
     TIMEVAL tv;
     tv.tv_sec = 2;
     tv.tv_usec = 0;
     int ret = select(0, &fdr, &fdw, &fde, &tv);
     switch (ret)
          case SOCKET_ERROR : printf("Socket Error\n");
          case 0 :               printf("Timeout\n");
          default :               if (fdr.fd_count) printf("Reading from socket is possible.\n");
                                   if (fdw.fd_count) printf("Writing to socket is possible.\n");
                                   if (fde.fd_count) printf("An exception occured.\n");


void main()
     WSADATA wsa;
     int ret = WSAStartup(MAKEWORD(1,1), &wsa);
     SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
     printf("\nnew socket\n");


     printf("\nconncting to www.netscape.com\n");

     sockaddr_in sa;
     memset(&sa, 0, sizeof(sockaddr_in));
     HOSTENT *hp = gethostbyname("www.netscape.com");
     memcpy((void*)&sa.sin_addr, (void*)(hp->h_addr_list[0]), 4);
     sa.sin_family = AF_INET;
     sa.sin_port = htons(80);
     connect(s, (sockaddr*)&sa, sizeof(sockaddr));


     printf("\nrequesting a page\n");

     char buffer[] = "GET \/index.html HTTP\/1.0\r\n\r\n";
     send(s, buffer, strlen(buffer), 0);

     ::Sleep(1000); //let's wait a second till they send us something


     printf("\n\n\nPress any key to continue...");


Explore More ContentExplore courses, solutions, and other research materials related to this topic.