Carcigenicate

Solution

Jul 24th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data NetException = NetNoException | NetTimeOut | NetRefused
  2.     deriving (Show, Eq)
  3.    
  4. diffExcept :: Either SomeException Handle -> Either NetException Handle
  5. diffExcept (Right h) = Right h
  6. diffExcept (Left (SomeException m))
  7.     | err == "WSAETIMEDOUT" = Left NetTimeOut
  8.     | err == "WSAECONNREFUSED" = Left NetRefused
  9.     | otherwise = error $ show m
  10.     where
  11.         err = reverse . dropWhile (== ')') . reverse . dropWhile (/='W') $ show m
  12.  
  13. main :: IO ()
  14. main = do
  15.     withSocketsDo $ do
  16.         putStr "Host?\n\t"
  17.         host <- getLine; putStrLn ""
  18.    
  19.         putStr "Port?\n\t"
  20.         p <- getLine; putStrLn ""
  21.         let port = read p :: Int
  22.    
  23.         good <- testAddress host port
  24.         print good
  25.    
  26.         main
  27.  
  28. testAddress :: HostName -> Int -> IO (Maybe Handle)
  29. testAddress host iPort = do
  30.     let port = PortNumber $ fromIntegral iPort
  31.     putStrLn $ "Testing - Host: " ++ host ++ ", Port: " ++ show iPort
  32.     result <- try $ connectTo host port
  33.    
  34.     let result' = diffExcept result
  35.     case result' of
  36.         Left NetTimeOut -> do print "Connection Timed Out"; return Nothing
  37.         Left NetRefused -> do print "Connection Refused"; return Nothing
  38.         Right h -> do
  39.             putStrLn $ "Connected to " ++ host
  40.             return $ Just h
Advertisement
Add Comment
Please, Sign In to add comment