socktest

Have you ever wanted to test a connection to only one port, and found nmap overkill, and you like to do it in C?
Normally I’d recommend something like
echo “~.” | telnet -r $H $X 2>&1| grep -i connected | wc -l | sed ‘s/ //g’`
But, if the host doesn’t answer the default tcp/ip timeout for a socket is 3 minutes!!!! You have to wait long
time…
You don’t want to wait too long for that, so you can use a program to test a socket connection, like socktest.c,
it tries to connect and if it can’t within 5 seconds it will bail out.
you should compile with gcc, if using solaris “gcc -o socktest -lsocket -lnsl socktest.c” will suffice.
So, for instance you want to test port 80 and port 44 in google.com:
bash-3.00$ ./socktest google.com 80 ; echo $?
Connection to port successful
bash-3.00$ ./socktest google.com 44 ; echo $?
ERROR: Timeout or error() 4 – Interrupted system call
1
You can get the exit code 0 as successful, 1 as not successful.
Source here:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#include <sys/fcntl.h>
//—————————————–
// Roberto Dircio Palacios-Macedo
// socktest – program to test a connection
// to a host in a specific port
// usage – ./socktest <host> <port>
//—————————————–
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
80/433
{
int res,valopt;
struct timeval tv;
fd_set myset;
socklen_t lon;
int soc, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3) {
fprintf(stderr,”usage %s hostname portn”, argv[0]);
exit(1);
}
portno = atoi(argv[2]);
server = gethostbyname(argv[1]);
soc = socket(AF_INET, SOCK_STREAM, 0);
if (soc < 0) {
error(“ERROR: opening socket”);
exit(1);
}
if (server == NULL) {
fprintf(stderr,”ERROR: no such hostn”);
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
long arg = fcntl(soc, F_GETFL, NULL);
arg |= O_NONBLOCK;
fcntl(soc, F_SETFL, arg);
res=connect(soc, &serv_addr,sizeof(serv_addr));
if (res < 0) {
if (errno == EINPROGRESS) {
tv.tv_sec = 5;
tv.tv_usec = 0;
FD_ZERO(&myset);
FD_SET(soc, &myset);
if (select(soc+1, NULL, &myset, NULL, &tv) > 0) {
lon = sizeof(int);
getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt) , &lon);
if (valopt) {
fprintf(stderr, “ERROR: Error in connection() %d – %sn”, valopt, strerror(valopt) );
exit(1);
}
}
else {
fprintf(stderr, “ERROR: Timeout or error() %d – %sn”, valopt, strerror(valopt) );
exit(1);
}
}
81/433
else {
fprintf(stderr, “ERROR: Error connecting %d – %sn”, errno, strerror(errno)) ;
exit(1);
}
}
arg = fcntl(soc, F_GETFL, NULL);
arg &= (~O_NONBLOCK) ;
fcntl(soc, F_SETFL, arg);
fprintf(stdout, “Connection to port successfuln”);
exit(0);
}
Enjoy!
82/433

Leave a Reply

Your email address will not be published. Required fields are marked *