Skip to content

Instantly share code, notes, and snippets.

@whoo
Created February 4, 2017 20:44
Show Gist options
  • Save whoo/fb3eb454d42cac1f9c1c9bc89dc6d920 to your computer and use it in GitHub Desktop.
Save whoo/fb3eb454d42cac1f9c1c9bc89dc6d920 to your computer and use it in GitHub Desktop.
int pingTCP(char *host)
{
int sockfd,ping=0;
struct hostent *hostent;
struct sockaddr_in sockaddr_in;
fd_set fdset;
struct timeval tv;
sockfd = socket(AF_INET, SOCK_STREAM, 6 );
hostent = gethostbyname(host);
sockaddr_in.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
sockaddr_in.sin_family = AF_INET;
sockaddr_in.sin_port = htons(80);
fcntl(sockfd, F_SETFL, O_NONBLOCK);
connect(sockfd, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in));
FD_ZERO(&fdset);
FD_SET(sockfd, &fdset);
tv.tv_sec = 0; /* 0 second timeout */
tv.tv_usec = 250*1000; /* 250ms second timeout */
if (select(sockfd + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &so_error, &len);
ping=1;
}
return ping;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment