http – 我想检查某个端口是否打开(Haskell)?

我想检查某个主机上是否有某个端口是打开的.我怎样才能做到这一点?在我调用了connectTo以及下一步后,我怎么才能真正知道端口是否打开?

main = do
  withSocketsDo $do
    h <- connectTo "some_host.com" $PortNumber 1234
    --- and....?

最佳答案 如果connectTo返回,则端口打开.否则会抛出异常

*** Exception: connect: failed (Connection timed out (WSAETIMEDOUT))

要么

*** Exception: connect: failed (Connection refused (WSAECONNREFUSED))

所以你可以做到

import Network(connectTo, PortID(..), PortNumber(..))
import Control.Exception(try, SomeException)
import System.IO(Handle)

isPortOpen :: String -> PortNumber -> IO Bool
isPortOpen host port = do
  h <- try $connectTo host (PortNumber port) :: IO (Either SomeException Handle)
  return $case h of
    Left _ -> False
    Right _ -> True
点赞