我想寫一個小Lwt(和電池)端口掃描器,以更好地 瞭解Lwt但是,我收到一個奇怪的例外,每當我嘗試掃描 太多端口在一次scan_ports_range。我懷疑我的機制 保持連接打開的最大數量是不工作...小Lwt端口掃描器不工作
Exception: Unix.Unix_error (Batteries.Unix.EMFILE, "socket",""). Fatal error: exception Sys_error("/home/(censored)/.opam/4.00.1/lib/utop: Too many open files")
(也崩潰UTOP BTW)
代碼如下。要觸發錯誤評估: scan_ports_range ~host:"127.0.0.1" (1000,2000)
我的lwt風格的任何批評/建議也是受歡迎的,因爲我只有 纔開始學習它。
open Lwt
let addr_parts addr =
let (host, port) = String.split addr ":" in (host, int_of_string port)
let addr ~host ~port =
lwt entry = Lwt_unix.gethostbyname host in
if Array.length entry.Unix.h_addr_list = 0 then begin
failwith (Printf.sprintf "no address found for host %S\n" host)
end;
return (Unix.ADDR_INET (entry.Unix.h_addr_list.(0), port))
let test_connection ?(timeout=1.0) addr =
let fd = Lwt_unix.socket Unix.PF_INET Unix.SOCK_STREAM 0 in
let connect_close =
(Lwt_unix.connect fd addr) >>= (fun() -> Lwt_unix.close fd) in
try_lwt
(pick [connect_close ; Lwt_unix.timeout timeout])
>>= (fun() -> return true)
with _ -> return false
let scan_ports ~host ~ports =
ports |> Lwt_list.map_p (fun port ->
lwt adr = addr ~host ~port in
test_connection adr >>= (fun res -> return (res,port)))
>>= (fun l -> return (l |> List.filter_map (function
| false, _ -> None | true, port -> Some(port))))
let scan_ports_range ?(max_open=20) ~host (a, b) =
let rec loop acc enum =
match Enum.peek enum with
| None -> acc |> List.concat |> List.rev |> return
| Some _ ->
let ports = enum |> Enum.take max_open |> List.of_enum in
let open_ports = scan_ports ~host ~ports in
open_ports >>= (fun l -> loop (l::acc) enum)
in loop [] (a--b)
你說得對。如果超時,我必須關閉文件描述符。 – rgrinberg