From 328c05713f968ccce7a63c934dce873dc7967d6a Mon Sep 17 00:00:00 2001 From: RblSb Date: Wed, 29 Jul 2020 18:06:27 +0300 Subject: Improve getGlobalIp --- src/server/Utils.hx | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) (limited to 'src/server/Utils.hx') diff --git a/src/server/Utils.hx b/src/server/Utils.hx index 40fa282..4e2fc9d 100644 --- a/src/server/Utils.hx +++ b/src/server/Utils.hx @@ -1,8 +1,9 @@ package server; -import sys.FileSystem; +import js.node.url.URL; import js.node.Https; import js.node.Os; +import sys.FileSystem; class Utils { @@ -11,16 +12,23 @@ class Utils { } public static function getGlobalIp(callback:(ip:String)->Void):Void { - // untyped to skip second null argument for node < v10 - Https.get(untyped "https://myexternalip.com/raw", r -> { + function onError(e):Void { + trace("Warning: connection error, server is local."); + callback("127.0.0.1"); + } + final url = new URL("https://myexternalip.com/raw"); + Https.get({ // this overload for node < v10.9.0 + timeout: 5000, + protocol: url.protocol, + host: url.host, + path: url.pathname + }, r -> { r.setEncoding("utf8"); final data = new StringBuf(); r.on("data", chunk -> data.add(chunk)); r.on("end", _ -> callback(data.toString())); - }).on("error", e -> { - trace("Warning: connection error, server is local."); - callback("127.0.0.1"); - }); + }).on("error", onError) + .on("timeout", onError); } public static function getLocalIp():String { -- cgit v1.2.3