1 /*
2 ** connect.c -- TCP/IP portion of the portmon daemon
3 ** Copyright (C) 2002 Nik Reiman <nik@aboleo.net>
4 **
5 ** This program is free software; you can redistribute it and/or modify
6 ** it under the terms of the GNU General Public License as published by
7 ** the Free Software Foundation; either version 2 of the License, or
8 ** (at your option) any later version.
9 **
10 ** This program is distributed in the hope that it will be useful,
11 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ** GNU General Public License for more details.
14 **
15 ** You should have received a copy of the GNU General Public License
16 ** along with this program; if not, write to the Free Software
17 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA
18 */
19 
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <errno.h>
23 #include <string.h>
24 #include <time.h>
25 #include <netdb.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #include <netinet/in.h>
30 #include <arpa/inet.h>
31 #include <sys/socket.h>
32 #include <sys/timeb.h>
33 #include <sys/types.h>
34 
35 #include "portmon.h"
36 #include "config.h"
37 
38 int sockfd;
39 int response;
40 
alarm_signal(int sig)41 void alarm_signal(int sig)
42 {
43  response = -3;
44  close(sockfd);
45  return;
46 }
47 
tcp_ping(struct sockaddr_in addr,int port)48 int tcp_ping(struct sockaddr_in addr, int port)
49 {
50  struct timeb start_time, end_time;
51 
52  ftime(&start_time);
53  response = 0;
54 
55  if(signal(SIGALRM, alarm_signal) == SIG_ERR) {
56   perror("SIGALRM");
57   exit(2);
58  }
59 
60  // create a socket
61  if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
62   snprintf(err_msg, STRLARGE, "Unable to create a socket\n");
63   log_write(err_msg);
64   return (-1);
65  }
66 
67  alarm(timeout);
68  if(connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) {
69   response = -2;
70  }
71  alarm(0);
72 
73  if(response == -2) {
74   snprintf(err_msg, STRLARGE, "Connection refused to %s:%d\n",
75            inet_ntoa(addr.sin_addr), port);
76   if(verbose) {
77    printf("connection refused\n");
78   }
79   log_write(err_msg);
80  }
81  else if(response == -3) {
82   snprintf(err_msg, STRLARGE, "Connection timed out to %s:%d\n",
83            inet_ntoa(addr.sin_addr), port);
84   if(verbose) {
85    printf("connection timed out\n");
86   }
87   log_write(err_msg);
88  }
89 
90  close(sockfd);
91 
92  ftime(&end_time);
93  if(response >= 0) {
94   response = (((int)end_time.time * 1000) + (int)end_time.millitm) -
95    (((int)start_time.time * 1000) + (int)start_time.millitm);
96   if(verbose) {
97    printf("response time %dms\n", response);
98   }
99  }
100  return (response);
101 }
102