Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better free port discovery #245

Merged
merged 3 commits into from
Jul 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 6 additions & 17 deletions src/etaoin/api.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1789,24 +1789,13 @@
;; network
;;

(defn connectable?
"Checks whether it's possible to connect a given host/port pair."
[host port]
(with-exception IOException false
(let [socket (java.net.Socket. ^String host ^int port)]
(if (.isConnected socket)
(do
(try (.close socket) (catch IOException _))
true)
false))))

(defn running?
"Check whether a driver runs HTTP server."
[driver]
(connectable? (:host @driver)
(:port @driver)))
(util/connectable? (:host @driver)
(:port @driver)))

(defn discover-port ;; todo move to utils
(defn discover-port
"Finds a port for a driver type.

Takes a default one from `defaults` map. If it's already taken,
Expand All @@ -1821,9 +1810,9 @@
Returns a port as an integer."
[type host]
(loop [port (or (get-in defaults [type :port])
(util/random-port))]
(if (connectable? host port)
(recur (util/random-port))
(util/get-free-port))]
(if (util/connectable? host port)
(recur (util/get-free-port))
port)))

;;
Expand Down
24 changes: 15 additions & 9 deletions src/etaoin/util.clj
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,18 @@
([tpl & args]
(error (apply format tpl args))))

(defn random-port
"Returns a random port skiping the first 1024 ones."
[]
(let [max-port 65536
offset 1024]
(-> max-port
(- offset)
(rand-int)
(+ offset))))
(defn get-free-port []
(let [socket (java.net.ServerSocket. 0)]
(.close socket)
(.getLocalPort socket)))

(defn connectable?
"Checks whether it's possible to connect a given host/port pair."
[host port]
(when-let [socket
(try
(java.net.Socket. ^String host ^int port)
(catch java.io.IOException _))]
(when (.isConnected socket)
(.close socket)
true)))