新手问题 关于一段扫描端口代码 (有注释)

drine · 2013年09月22日 · 最后由 kevinxu 回复于 2013年09月22日 · 2309 次阅读
require 'socket' 
def open_port(host, port)                   #test whether if the port is open 
  sock = Socket.new(:INET, :STREAM)
  raw = Socket.sockaddr_in(port, host)
  puts "#{port} open." if sock.connect(raw)
  rescue (Errno::ECONNREFUSED)    
end                                         #end of the function
def main(host, start_port, end_port)    
  start_port =1

  if start_port<(end_port/2)
  a = Thread.new { loop do
    open_port(host,port)
    start_port = start_port + 1
  if start_port == (end_port/2)
    break
  end                                       #end of the nearest "if"
    end                                     #end of the nearest "loop"
  }

    a.join
  end

  if start_port>(end_port/2)
  b = Thread.new { loop do  
    open_port(host,port)
    start_port = start_port + 1
    if start_port == end_port
      break
    end                                     #end of the nearest "if"
    end                                     #end of the nearest "if"
    }
    b.join
  end
end
main ARGV[0], ARGV[1].to_i, ARGV[2].to_i
  • #扫描端口,若打开,显示#port if open
  • 第一段函数单独测试过没有问题
  • 问题出在 main 函数内
  • #输入:ruby *.rb "host" "start-port" "end-port"

哪里出问题了额。。改了半天。。囧

@DrinE 仔细看下你 main 里面 open_port(host, port)

你这个 port 有传参数进去么?

报错贴出来~ 可以发现的问题是:loop 在线程内 但是操作的资源 start_port 等在线程外 这个很容易出问题

#3 楼 @zj0713001 啊,我改回去了..在哪里看到的 start_port 等在线程外了?就是 cmd 运行后的报错内容里么。。没注意 = =

稍稍重写了一下你的代码,没试过,不知道可行性如何,有没有错误

require 'socket' 

def open_port(host, port)                   #test whether if the port is open 
  sock = Socket.new(:INET, :STREAM)

  begin
    raw = Socket.sockaddr_in(port, host)
    puts "#{port} open." if sock.connect(raw)
  rescue
    Errno::ECONNREFUSED
  end
end                                         #end of the function

def main(host, start_port, end_port)    
  start_port = 1
  another_port = end_port / 2

  the_ending_port = case
  when start_port < another_port then another_port
  when start_port > another_port then end_port
  end

  Thread.new { start_port.upto(the_ending_port) { |port| open_port(host, port) } }.join
end

还是不能太适应 rescue 单独使用,所以强制加上了 begin,

另外,start_port == end_port / 2,你怎么办?我看你 if 里面没有涉及到。

所以 the_ending_port 我只能用 case when 了,就没用三目运算 the_ending_port = (start_port < another_port) ? another_port : end_port

#5 楼 @zfjoy520 对。。想靠端口数..写 2 线程的时候短路忘了考虑 start_port 和 end_port 之间的关系...囧 之后自己也发现这个很 2 的问题了。。

用 nmap 或者 nc 如何

需要 登录 后方可回复, 如果你还没有账号请 注册新账号