地址端口检测

C/C++, Linux, Unix No Comments »

       有时候我们需要对某些服务器是否可用进行判断,一般可以通过telnet ip  port  的方式来实现,这时如果返回的是Connection refused或是Escape character is ‘^],则表示这个端口是开放的,不过前者拒绝该请求,而后者则可以正常联通。如果我们需要一次性检测一批端口是否开放,这时如果一条条输telnet命令可能就有些累了。下面说一下如何用脚本来实现。

      首先我们需要一个可以探测端口的程序,这个我是用c语言来实现的(参考了网上的代码,如果谁发现可用的命令欢迎告诉我哦),通过编译后就可以运行,不过它只实现扫描一个端口的功能。后面会再介绍个shell脚本来实现多次调用该程序来实现扫描多个地址的目的。

      具体c语言的代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <time.h>
#include <arpa/inet.h>

/* 该代码可以用来测试某个端口是否联通,使用方法 a.out 128.32.171.33 23
*  然后查看$?的值,如果是0,则表示该端口可以联通,否则不可以联通
*  可以和shell脚本结合使用
*  文件名:detect_ip_port.c
*/

int main(int argc, char *argv[])
{
 int fd, retval;
 struct sockaddr_in addr;
 struct timeval timeo = {3, 0};
 char buf[1024];
 int i;
 socklen_t len;
 fd_set set;

 fd = socket(AF_INET, SOCK_STREAM, 0);
 addr.sin_family = AF_INET;
 addr.sin_addr.s_addr = inet_addr(argv[1]);
 addr.sin_port = htons(atoi(argv[2]));
 if ((i=connect(fd, (struct sockaddr*)&addr, sizeof(addr))) == 0)
 {
  close(fd);
  perror("connected success:");
  return 0;
 }
 perror("connected error:");
 close(fd);
 return 1;
}

可以通过执行shell命令,来生成可执行文件:

gcc –o detect_one_addr  detect_ip_port.c

为了实现一次扫描多个地址的目的,我首先采用一个txt文件来保存需要扫描的ip 和port等信息,具体txt的内容大致如下:

192.168.0.1 8000 01 服务器1
192.168.0.2 8000 02 服务器2
192.168.0.3 8000 03 服务器3
192.168.0.4 8000 04 服务器4
192.168.0.5 8000 05 服务器5

其中每一行中包括ip  port  编号  名称,每个字段用空格或tab分隔。在此我们假设该文件名称为:servers.txt

接下来使用shell脚本来实现扫描多个地址的目的:

#!/usr/bin/sh

# file name : detect_all.sh

detect_one_addr()
{
 ip=`echo $line |  awk '{print $1}'`
 port=`echo $line |  awk '{print $2}'`
 entr_no=`echo $line |  awk '{print $3}'`
 entr_name=`echo $line |  awk '{print $4}'`

 ./detect_ip_port $ip $port
 if [ $? == 0 ] ; then
 	echo "$entr_no  $entr_name  is OK"
 else
 	echo "$entr_no $entr_name is Failed"
 fi
}

testfile="servers.txt"
while read -r line
do
    detect_one_addr $line
done < $testfile

然后在命令行中执行detect_all.sh即可实现该扫描的功能。你可能会发现如果某个端口不开放,该程序需要过好长时间才会超时,这个超时时间是由系统来决定的,具体是TCP连接的超时时间,一般不建议修改。我也经常遇到连接一个端口经过好久最后联通的情况,因为首次连接需要进行ARP、或是路由器会帮你建立连接(因为这个连接好久不用可能已经休息了,呵呵),所以耐心等待就好。

PS:经过上述程序可以看出,我们可以通过shell或是其他高级语言,如ruby,perl等来做高级的工作,然后我们用c/c++、java等实现底层的功能,这样可以更有效率的解决问题,充分发挥各个语言的优点

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS 登录