How to check port availability in client-side JavaScript? - javascript

Is it possible to detect in JavaScript (in the browser) if a port is disabled by the firewall or router?

No, with pure javascript this is not possible (aside of making http requests to the specific ports, but those results mean little), what you can do however is check from the outside (in other words your server) whether the specific port is open. Another option would be to use a java applet or browser plugin which could do this for you if you really need it, in which case there are various open source tools which you could probably port if you have the necessary experience with those. Do note however that this isn't exactly user friendly. (Either way, it would be useful if you would describe the exact scenario where you need this, as there might be an altogether different solution.)

You can only see if the expected response is there or not.
One has to stay in the boundaries of HTTP when using javascript.
Of course you can send an Ajax request on whatever port of server and see if you get an error. If you want to check port for current machine then probably sending a request on "localhost:843" could help.
But the error could be of some other reasons and not necessarily firewall issue.
We need more information to help you out.

If you are flexible enough to use jQuery, then see this Answer by me. This will not only check the availability of port, but also whether a success response code 200 is coming from the remote (or any , I meant it supports cross-domain also) server. Also giving the solution here. I will be checking here for port 843.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.7.2-min.js"></script>
</head>
<body>
<script type"text/javascript">
var isAccessible = null;
function checkConnection() {
/*make sure you host a helloWorld HTML page in the following URL, so that requests are succeeded with 200 status code*/
var url = "http://yourserverIP:843/test/hello.html" ;
$.ajax({
url: url,
type: "get",
cache: false,
dataType: 'jsonp', // it is for supporting crossdomain
crossDomain : true,
asynchronous : false,
jsonpCallback: 'deadCode',
timeout : 1500, // set a timeout in milliseconds
complete : function(xhr, responseText, thrownError) {
if(xhr.status == "200") {
isAccessible = true;
success(); // yes response came, execute success()
}
else {
isAccessible = false;
failure(); // this will be executed after the request gets timed out due to blockage of ports/connections/IPs
}
}
});
}
$(document).ready( function() {
checkConnection(); // here I invoke the checking function
});
</script>
</body>
</html>

Related

Ajax URL appears blocked by company firewall

I am working on an ajax function that loads another page as a way to get around iframe limitations on Shopify. My issue seems to be that the URL is blocked or headers stripped. Nothing too complex, everything worked as I needed it to by using the following:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
<button onclick="get_report()">Get</button>
<div id="content_div"></div>
This works through public networks with no problem. However, when my client uses it behind a company firewall it fails to load the page. Upon further inspection it appears that the site URL my php is hosted on cannot be loaded either (I cannot be there to physically confirm). Here is a sample of that page if its relevant:
<?php
$allowedOrigins = [
"https://myexample.com",
"https://myexample2.com"
];
if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$origin = $_SERVER['HTTP_ORIGIN'];
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
$origin = $_SERVER['HTTP_REFERER'];
} else {
$origin = $_SERVER['REMOTE_ADDR'];
}
if (in_array($origin, $allowedOrigins)) {
header("Access-Control-Allow-Origin: " .$origin);
}
setcookie('cross-site-cookie', 'name', ['samesite' => 'None', 'secure' => true]);
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TEST ALT IFRAME</title>
</head>
<body>
<div><?php echo "IT WORKS"; ?></div>
</body>
</html>
What I know:
-Walked client through accessing chrome console, zero errors listed
-URL never loads when client tries to load it via browser
-Ajax never gives an error response
-Webmaster/IT team is unreachable (I have tried to contact them for at least 4 months)
What I've tried:
-Recently adding meta tags and !DOCTYPE (just in case)
-Validating both the iframe site and URL site with W3C
-Confirming both the iframe site and URL site work with VPN and public networks
-Checking for correct categorization on major network filtering groups (semantics, paleo-alto, etc) and set to 'SAFE'.
My Question:
-How do I find out if the URL is blocked or the ajax request is being stripped?
-If the network is filtering my ajax URL am I at a dead end or is there another option?
How do I find out if the URL is blocked or the ajax request is being stripped?
If there's a network error, you can respond to it in the error callback you pass to the AJAX call:
function get_report() {
var params = {
type: "GET",
url: "https://example.com/mypage.php",
dataType: 'html',
success:function(html) {
$("#content_div").load("https://example.com/mypage.php");
},
error: function(XMLHttpRequest, textStatus) {
// inspect XMLHttpRequest to determine if network error occurred
alert('Error : ' +XMLHttpRequest.response);
}
};
jQuery.ajax(params);
};
If the network is filtering my ajax URL am I at a dead end or is there another option?
You're sort of at a dead end at the application level, unless you're willing to do something really convoluted like have a third party service, that you know will not have firewall restrictions, request the page, and then forward it to a service that is accessible from behind that firewall. So the short answer is, no, not really (at least not practically)

Checking if a URL exists or not in Client Side Code

My objective is to check whether a URL is valid or not from client side. I tried the following things:
1. Tried using a ajax request using dataType as JSON. - Got the Cross-Origin Request Blocked error.
2. Tried using the JSONP as datatype. - Worked fine for some websites like google.com but it cribed for others like facebook.com
Got the error like "Refused to execute script from
FaceBook
callback=jQuery32107833494968122849_1505110738710&_=1505110738711'
because its MIME type
('text/html') is not executable, and strict MIME type checking is enabled."
Is there any workaround for this. I just want to make sure that the URL is valid irrespective of the content in the response.
Following is the code I wrote:
<html>
<body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
function CallPageMethod() {
$.ajax({
type: "GET",
url: "https://www.google.com/",
dataType: "jsonp",
success: function (data, textStatus, xhr) {
alert("Success");
},
error: function (data, textStatus, xhr) {
if (data.status === 200) {
alert("Finally I am done")
} else {
alert("Error");
}
},
});
}
</script>
<Button onclick="CallPageMethod()">Test URL</Button>
</body>
</html>
Any Suggestions or any alternative approach that I should follow to resolve this issue?
Not properly, but Most sites have a favicon.ico either from the site directly or provided from the hosting company for the site if it is a 404 image.
<img src="https://www.google.com/favicon.ico"
onload="alert('icon loaded')">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
onload="alert('ajax loaded')"></script>
Although iframe and object do have onload events, invalid pages also trigger the event.
This would be the fastest site test I can think of ...
var img = new Image();
img.onload = function () {
alert("image width is " + img.naturalWidth + " not zero so site is valid");
}
img.src = "https://www.google.com/favicon.ico";
As for facebook, the each page uses resources from another url, iframes are blocked as well as scripts. You would need to make the request from a server to test if a page existed.
You're best off writing a proxy on your server so:
Client hits your server with the URL you want to check
Your server makes the request to that URL and gets a response (or not)
Server returns status code to the client
This way will avoid the CORS issues you're having to navigate and will allow you to set any HTTP headers you need to.

Small Webpage to check open ports on IP [duplicate]

This is solved at last with "timeout" attribute of jQuery AJAX (and JSONP). See my own answer !
Please see the updated part, I have tried with applet too. And will not hesitate to accept your answer if you can give a solution with applet implementation.
I am working with a Java based web application. My requirement is to check whether a particular port (say 1935) is open or blocked at client's end. I have implemented a "jsonp" (why 'jsonp' ? i found that 'http' request through AJAX cannot work for corssdomain for browsers 'same origin policy') AJAX call to one of my server containing particular port. And if the server returns xhr.status == 200 the port is open. Here is a drawback that I can't make the execution-flow wait (synchronous) until the call completes. Here is the JavaScript function I am using.
Any alternative solution (must be a client-sided thing must be parallel with my application, please dont suggest python/php/other languages) is also welcome. Thanks for your time.
function checkURL() {
var url = "http://10.0.5.255:1935/contextname" ;
var isAccessible = false;
$.ajax({
url: url,
type: "get",
cache: false,
dataType: 'jsonp',
crossDomain : true,
asynchronous : false,
jsonpCallback: 'deadCode',
complete : function(xhr, responseText, thrownError) {
if(xhr.status == "200") {
isAccessible = true;
alert("Request complete, isAccessible==> " + isAccessible); // this alert does not come when port is blocked
}
}
});
alert("returning isAccessible=> "+ isAccessible); //this alert comes 2 times before and after the AJAX call when port is open
return isAccessible;
}
function deadCode() {
alert("Inside Deadcode"); // this does not execute in any cases
}
---------------------------------------------------------UPDATE----------------------------------------------------------------
I have tried with Java Applet (thanks to Y Martin's suggestion). This is working fine in appletviewer. But when I add the applet in HTML page, it is giving vulnerable results. Vulnerable in the sense, when I change the tab or resize the browser, the value of portAvailable is being altered in the printed message.
Applet Code :
import java.applet.Applet;
import java.awt.Graphics;
import java.net.InetSocketAddress;
import java.net.Socket;
public class ConnectionTestApplet extends Applet {
private static boolean portAvailable;
public void start() {
int delay = 1000; // 1 s
try {
Socket socket = new Socket();
/*****This is my tomcat5.5 which running on port 1935*************/
/***I can view it with url--> http://101.220.25.76:1935/**********/
socket.connect(new InetSocketAddress("101.220.25.76", 1935), delay);
portAvailable = socket.isConnected();
socket.close();
System.out.println("init() giving---> " + portAvailable);
}
catch (Exception e) {
portAvailable = false;
System.out.println("init() giving---> " + portAvailable);
System.out.println("Threw error---> " + e.getMessage());
}
}
public void paint(Graphics g) {
System.out.println("Connection possible---> " + portAvailable);
String msg = "Connection possible---> " + portAvailable;
g.drawString(msg, 10, 30);
}
}
And this is my HTML page (I am hosting it on same computer with a different Tomcat 6 which runs on port 9090. I can view this page with url ---> http://101.220.25.76:9090/test/):
<html>
<body>
<applet code="ConnectionTestApplet" width=300 height=50>
</applet>
</body>
</html>
And how I am doing the port 1935 blocking and openning ?
I have created firewall rule for both inbound and outbound for port 1935.
I check the port 1935 open/blocked scenario by disabling/enabling both rules.
This is my S.S.C.C.E. Now please help me :)
Gotcha !!! I have solved my problem with JSONP and jQuery AJAX call. I discovered the timeout attribute of jQuery AJAX and my code executed fluently when the port was blocked or opened. Here is the solution for future visitors. Thanks to all answerers for contribution.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="jquery-1.7.2-min.js"></script>
</head>
<body>
<script type"text/javascript">
var isAccessible = null;
function checkConnection() {
var url = "http://101.212.33.60:1935/test/hello.html" ;
$.ajax({
url: url,
type: "get",
cache: false,
dataType: 'jsonp', // it is for supporting crossdomain
crossDomain : true,
asynchronous : false,
jsonpCallback: 'deadCode',
timeout : 1500, // set a timeout in milliseconds
complete : function(xhr, responseText, thrownError) {
if(xhr.status == "200") {
isAccessible = true;
success(); // yes response came, esecute success()
}
else {
isAccessible = false;
failure(); // this will be executed after the request gets timed out due to blockage of ports/connections/IPs
}
}
});
}
$(document).ready( function() {
checkConnection(); // here I invoke the checking function
});
</script>
</body>
</html>
I don't think you understand the use cases for JSONP and it's not possible to test open ports with it. http://en.wikipedia.org/wiki/JSONP
If you want a client side solution it could be possible with websockets, but this is only available on new browsers like chrome or ff. Otherwise request a server side script which does the ping. For example - with a curl script: curl and ping - how to check whether a website is either up or down?
Here is a Java code as an Applet to test server/port connectivity:
import java.io.*;
import java.net.*;
public class ConnectionTestApplet extends Applet {
public void start() {
boolean portAvailable = false;
int delay = 1000; // 1 s
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("server.domain.com", 1935), delay);
portAvailable = socket.isConnected();
socket.close();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Connection possible: " + portAvailable);
}
}
You still have to get the information out of the applet to do something else with that result. The easiest way is to redirect the browser thanks to getAppletContext().showDocument(url)
Instead of an applet a flash component may be used. Using the Socket class available in ActionCcript one can open a tcp connection from flash to a port on a server to check if its open. But based on the flash player version a policy file needs to be placed on the server to which the socket is opened.
Check this out:
http://blog.andlabs.org/2010/12/port-scanning-with-html5-and-js-recon.html
With JS-Recon, you can do port scanning with javascript. You can simply point it to your local IP address. I believe it works by making a web sockets/cors connection to an arbitrary desintation ip/socket and measuring the timeouts. It is not a perfect approach, but this may be the limit of javascript ultimately.
If you can do it in a java applet/flash application, that may be better ultimately as they have lower-level access.
You cannot do this in JavaScript because it doesn't have true socket support, with JavaScript you can only test for the presence of HTTP socket. You could use Java (JavaScript is not Java) and write a proper Java Applet to do it.
You should also read this Q&A How to Ping in java
Try using isReachable
In JavaScript, you have to work-around the asynchronous issue. Here is a proposal:
The HTML page displays an animated image as a progress bar
You invoke the checkURL
After either receiving the callback or a defined timeout, you change display for an error message or do on with the job to do
Based on the following document with the use of XMLHttpRequest, here is a code example for checkURL:
var myrequest = new ajaxRequest();
var isAccessible = false;
myrequest._timeout = setTimeout(function() {
myrequest.abort();
displayErrorMessage();
},
1000
) //end setTimeout
myrequest.onreadystatechange = function() {
if (myrequest.readyState == 4) { //if request has completed
if (myrequest.status == 200) {
isAccessible = false;
goOnWithTheJob();
} else {
displayErrorMessage();
}
}
myrequest.open("GET", url, true);
myrequest.send(null); //send GET request
// do nothing - wait for either timeout or readystate callback
This code lets 1 second to get the 200 response from a HTTP GET on a basic resource.
In your local test, you get an immediate answer because the system answers connection reset if the port is closed but a firewall just does not answer.
Even if the open method may be used synchronously, I recommend the use of a timer because the code is likely to wait for TCP timeouts and retries (3 x 1 minute ?) as a firewall usually just drops packets on closed ports and may reject ICMP packets, preventing you to test availability thanks to ping. And I imagine such a long wait is not expected for such a check.
I am occasional frontend/javascript/jQuery guy, so this may not be 100% professional, but it is good enough and it solved my similar problem:
ping_desktop_app = $.get({
url: "http://127.0.0.1:#{desktop_app_port}",
dataType: 'jsonp',
})
$(#).parent().find(".click-me-to-use-desktop-app").click ->
if ping_desktop_app.status == 200
$.get({
url: "http://127.0.0.1:#{desktop_app_port}/some_command/123123",
dataType: 'jsonp',
})
else
alert("Please run your desktop app and refresh browser")
I could not check whether port is open (desktop app is running) on server side because views are cached, so I needed to check the localhost/port right before user click in browser
Edits translating to JS are welcome

Why does JavaScript alert display an empty string in Phonegap Android App while the code is working perfectly fine on browser?

I'm working on a simple PhoneGap application that communicates with a server that runs PHP, gets a string and displays it in JavaScript alert.
The App works perfectly fine on a browser. The JavaScript alert displays the string returned by the PHP code on the server. This action happens on click event of a button.
Here is the markup:
<!DOCTYPE html>
<html xml:lang="en" lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;">
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="jquery.min.js"></script>
<script src="cordova.js" charset="utf-8" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" src="index.js"></script>
</head>
<body>
<h1>Hello World!</h1>
<button id="eventfire">Click</button>
</body>
</html>
JS code
$(document).ready(function(){
$("#eventfire").click(function(){
var data = {
"action": "test"
};
data=$.parseJSON('{ "name": "John" }');
$.ajax({
type: "POST",
dataType: "text",
url: "http://192.168.x.x/HelloWorldTest/response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
alert(data);
alert("type is " + typeof data + ". Length is " + data.length);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
},
statusCode: {
400: function () {
alert("Bad request!");
},
401: function() {
alert("Unauthorized!");
},
403: function() {
alert("Forbidden!");
},
404: function() {
alert("Page not found!");
},
408: function() {
alert("Request Timeout!");
},
200: function() {
alert("page reached");
},
}
});
});
})
PHP code
<?php
echo 'john';
?>
When I run this code on a AVD, the alert does not display the string. I have never seen such a alert getting displayed. The alert displayed inside the success function is shown below.
On inspecting this string, I understood that the length is 0.
I was able to reproduce the same issue on browser with a string of 0 characters length.
I'm not sure why the piece of code that is working fine when run on browser but acts weirdly on AVD. The string was getting displayed as expected on browser but not on AVD.
Find below the screenshots of the same code displaying the correct alert on browser.
I want to know the possible reasons of why the string from PHP is getting lost ?
I've never used PhoneGap but since your php file is stored on a different server than the files trying to call it, you will need to enable Cross-Origin Resource Sharing (CORS) (though I can't be sure this is the only issue)
Try adding Header set Access-Control-Allow-Origin "*" in your server's .htaccess file
By default, servers block access to resources like php files when the request comes from a file that is not stored on the same server.
For example, if I have a js file located at http://myfirstwebsite.com/awesome.js and in that file I make an ajax call to http://mysecondwebsite.com/loadstuff.php, the request will be blocked by the server and will produce the following error in the console:
XMLHttpRequest cannot load http://mysecondwebsite.com/loadstuff.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysecondwebsite.com' is therefore not allowed access.
I'm not sure if you can see this error in PhoneGap or where as I have never used it.
As the warning alludes to, in order to fix this, you must set the 'Access-Control-Allow-Origin' header to allow remote files to access the ones on your server.
Here is a tutorial explaining how to do that on Ubuntu
Just in case that link ever dies, here are the steps (copied right from that site)
Make sure you have the mod_headers Apache module installed. to do this check out /etc/apache2/mods-enabled/ and see if there’s a ‘headers.load’ in there. If there isn’t then just sudo ln -s /etc/apache2/mods-available/headers.load /etc/apache2/mods-enabled/headers.load
Add the Access-Control-Allow-Origin header to all HTTP responses. You can do this by adding the line Header set Access-Control-Allow-Origin "" to the desired section in your configuration file (like the /etc/apache2/sites-available/default file). Saying "" will allow cross-site XHR requests from anywhere. You can say "www.myothersite.com" to only accept requests from that origin.
Reload apache server. sudo /etc/init.d/apache2 reload

"Uncaught SyntaxError: Unexpected token" when parse jsonp

I have created a json webservice in ASP.NET.
URL http://mydomain:21130/JSONdata.aspx?Option=GetListRootMenus
Data return:
{"NumberOfMenu":"2", "Menus":[{"MenuKey":"menu_home", "MenuLevel":"1" },{"MenuKey":"menu_info", "MenuLevel":"1" }]}
After that, i parsed via JSONP
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.getJSON demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p> this is a param </p>
<script>
$(document).ready(function(){
console.log("zc");
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "http://mydomain:21130/JSONdata.aspx?Option=GetListRootMenus&callback=?",
success: function(data) {
console.log("123");
},
error: function(){
console.log("456");
}
});
});
</script>
</body>
</html>
but wrong. i don't know why :(
As I explained in my comment, your service returns JSON, while jQuery expects JSONP. This is an issue because the response will be evaluated as JavaScript, but you are not sending back valid JavaScript.
Since you have control over the server, you have three possible solutions:
1. Tell jQuery to expect JSON
If there are no cross-domain issues because the site itself is also served from that domain, simple let jQuery make a real Ajax request, by changing dataType to json and removing callback=? from the URL.
2. Enable CORS (and tell jQuery to expect JSON)
If there are cross-domain issues, you can still do what I said in the first solution, but in addition, enable CORS on your server. In short, this allows other sites to make Ajax requests to your server. Have a look at http://enable-cors.org/ to learn how to enable it for your server.
3. Return JSONP
JSONP is all about including JavaScript dynamically. This works across domains because <script> elements don't have the same-origin restriction that Ajax has. However, it is still something that the server has to support because it has to return valid JSON. If your JSON response was
{"foo": 42}
then the JSONP response would be
func({"foo": 42});
The name of the function (func) in this example, is taken from some GET parameter that you could choose arbitrarily, but most common is callback. jQuery will actually choose a random function name so it will send something like
callback=jQuery123135343456456
your service has to take that value and use it as function name for JSONP, i.e.
jQuery123135343456456({"foo": 42});
See also
What is JSONP all about?
What are the differences between JSON and JSONP?

Categories

Resources