gpt4 book ai didi

java - Scala 中的端口扫描 : Application hangs for a closed port on the remote host

转载 作者:行者123 更新时间:2023-12-01 22:35:12 25 4
gpt4 key购买 nike

我一直在尝试创建一个需要尽快扫描网络(主要是 LAN)上的开放端口的应用程序。

我四处搜索,发现一个很好的方法使用以下代码:

(1 to 65536).par.map { case port ⇒
try {
val socket = new java.net.Socket("127.0.0.1", port)
socket.close()
println(port)
port
} catch {
case _: Throwable ⇒ -1
}
}.toSet

但是,代码的问题是,如果我输入 127.0.0.1 或 localhost 以外的任何内容作为位置(例如 192.168.1.2),应用程序就会卡住。

知道为什么会发生这种情况以及如何解决它吗?

附注我还尝试使用 socket.setSoTimeout(1500) 设置套接字超时,但没有变化。

最佳答案

类似

import scala.concurrent.{Future, Await}
import scala.concurrent.duration._
import scala.util.Try
import scala.concurrent._
import java.util.concurrent.Executors

implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(100))

def openPorts(address:String ="127.0.0.1",duration:Duration = 10 seconds, fromPort:Int = 1, toPort:Int = 65536) = {
val socketTimeout = 200
val result = Future.traverse(fromPort to toPort ) { port =>
Future{ Try {
val socket = new java.net.Socket()
socket.connect(new java.net.InetSocketAddress(address, port),socketTimeout)
socket.close()
port
} toOption }
}
Try {Await.result(result, duration)}.toOption.getOrElse(Nil).flatten
}


scala> val localPorts openPorts(fromPort = 10, toPort = 1000)
localPorts: scala.collection.immutable.IndexedSeq[Int] = Vector(22, 631)
scala> val remotePorts = openPorts(fromPort = 10, toPort = 1000, address="192.168.1.20")
remotePorts: scala.collection.immutable.Seq[Int] = List() //we ate the timeout

scala> val remotePorts = openPorts(fromPort = 12000, toPort = 13000, address="91.190.218.61", duration=30 seconds)
remotePorts: scala.collection.immutable.Seq[Int] = Vector(12345, 12350)

关于java - Scala 中的端口扫描 : Application hangs for a closed port on the remote host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25000930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com