Currently I am using URL()
public boolean isInternetAvailable(){
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
urlConnect.setConnectTimeout(5000);
Object objData = urlConnect.getContent();
return true;
} catch (Exception e) {}
return false;
}
But In the requirement, we don't want to use any URL. We want to ping localhost if connection is available than return true otherwise flase.
For nslookup I am using
try
{
InetAddress inetAddress = InetAddress.getByName("localhost");
System.out.println("Host: " +inetAddress.getHostName());
System.out.println("IP Address: " +inetAddress.getHostAddress());
System.out.println("IP Address: " +inetAddress.isSiteLocalAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
But I am not understand how to check the connection availability with nslookup.
Please suggest best approach for it. Thanks
There are several catches to this question:
Starting with the most specific one - connecting to localhost: even if your computer does not have a network card, it will be able to resolve localhost on a loopback interface and connect to itself (if there is an open port).
Your DNS may be down/misconfigured, so you cannot resolve example.com but you can connect to it by IP (93.184.216.34) - does that mean than "internet is not available"?
The firewall in your company may be blocking certain sites, but allowing other - does that mean than "internet is not available"?
The server of example.com is down while all the other sites in the world work fine. Does that mean than "internet is available" or not?
The firewall in your company may be allowing HTTP connections only on standard ports 80 and 443 and disallowing other. Thus, http://example.com connects, but http://example.com:12345 does not. Does that mean than "internet is available" or not?
So the only question you can actually ask is whether you can connect to a particular host on a particular port using its domain name and/or its IP address.
Figured out a final solution using NetworkInterface:
Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces();
while(eni.hasMoreElements()) {
Enumeration<InetAddress> eia = eni.nextElement().getInetAddresses();
while(eia.hasMoreElements()) {
InetAddress ia = eia.nextElement();
if (!ia.isAnyLocalAddress() && !ia.isLoopbackAddress() && !ia.isSiteLocalAddress()) {
if (!ia.getHostName().equals(ia.getHostAddress()))
return true;
}
}
}
I have got solution from here:- Java Quickly check for network connection
Related
I have a java application that pulls information from network interface and I'm using NetworkInterface class to iterate through the gazillion of interfaces I have in my computer. "I have installed virtualbox" and this create many virtual interface. But I need to get info from my wireless or ethernet interface as those are the only option to connect to the network. The problem is that I want to be able to sort through all these interfaces and get only the relevant. What approach you guys suggest? doing a search through the NetworkInteface collection looking for eth0 or wlan1. any ideas appreciated. Here's the code that deals with network interface in my application.
//displaying all network interface
Enumeration<NetworkInterface> nets = null;
try {
nets = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e3) {
e3.printStackTrace();
}
for (NetworkInterface netint : Collections.list(nets)) {
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
System.out.printf(count + " Display name: %s\n", netint.getDisplayName());
System.out.printf("Name: %s\n", netint.getName());
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
System.out.printf("InetAddress: %s\n", inetAddress);
}
System.out.println("\n");
}
There could be a more straightforward way, but if you're just looking for the interface that connects to the internet, there's a simple trick you can use that doesn't involve reading routing tables - just create a socket, connect it to an address that exists on the internet, then get that socket's local address. It's better to use a UDP socket since its connect doesn't do any actual IO:
DatagramSocket s = new DatagramSocket();
s.connect(InetAddress.getByName("1.1.1.1"), 53);
System.out.println(s.getLocalAddress());
The operating system will bind the socket to an appropriate interface for the outbound connection using the routing table. Once you have the IP address, you can find the interface with that IP address.
I want to validate that given IP and port are running in MQTT if not then i have to show exception to user. here is my code,
try {
MqttMessage message2 = new MqttMessage();
MQTT mqtt_connect = new MQTT();
mqtt_connect.setHost(Host_Address, port);
String topic = "/call/MQTT_Config";
mqtt_connect.setClientId("MQTT_Config");
mqtt_connect.setWillRetain(false);
mqtt_connect.isWillRetain();
mqtt_connect.setWillTopic(topic);
BlockingConnection m_publisher = mqtt_connect.blockingConnection();
m_publisher.connect();
if(m_publisher.isConnected()){
System.out.println("connected");
m_publisher.disconnect();
}
else
{
System.out.println("not connected");
return "Port or IP may not running";
}
} catch (Exception e) {
e.printStackTrace();
return "failure";
}
when i give correct IP and port then it goes to if(m_publisher.isConnected()) condition fine but when i give wrong IP or port then it comes till m_publisher.connect(); and then there is nothing happen, like loading console only.Is not going to next step. why?
i have to show some validation when user give unmatched IP or MQTT port. where am i doing wrong?
The problem here will depend on what the user enters.
If they enter an IP address for a machine that exists but is not listening on the port then the machine will respond quickly with a connection refused message
If they enter an IP address for a machine that doesn't exist then the code will wait for the TCP timeout (default is 15mins) before raising an error.
I am trying to build a proxy server and recently I am working on https. As specified in this post. I've tried to tunnel Connect request. My Code is as:
private boolean handleConnect(HttpServletRequest req,HttpServletResponse response){
String uri=req.getRequestURI();
String port="";
String host="";
int c=uri.indexOf(":");
if (c >= 0){
port = uri.substring(c + 1);
host = uri.substring(0,c);
if (host.indexOf('/') > 0)
host = host.substring(host.indexOf('/') + 1);
}
// Make Asyncronous connection
try{
InetSocketAddress inetAddress = new InetSocketAddress(host,Integer.parseInt(port));
{
InputStream in=req.getInputStream();
OutputStream out=response.getOutputStream();
if(true){
Socket sock=new Socket(host,Integer.parseInt(port));
IO.copy(in, sock.getOutputStream());
IO.copy(sock.getInputStream(), out);
if(!sock.getKeepAlive()){
sock.close();
}
}
}
}
catch(Exception ex){
ex.printStackTrace();
return false;
}
return true;
}
The code results java.net.UnknownHostException: google.com.np for https://google.com.np and Timeouts for https://Facebook.com . Why is that ??
Please suggest best way to tunnel Connect HTTP request.
Your UnknownHostException is due either to a non-existent host or a misconfigured DNS, and your connect timeout to a network connectivity problem, neither of which are on-topic here, but you can't really write a proper proxy this way. You need to start two threads per connection, one to copy bytes in each direction.
I am writing a telnet like program in java using the server socket and socket classes. This is my current code for the client program. The user types in the server name and the port they would like to connect on.
static Socket getSocket()
{
while(true)
{
System.out.println("What server do you want to connect to on which port?");
String info = sc.nextLine();
String host = info.split(" ")[0];
int port = Integer.parseInt(info.split(" ")[1]);
try
{
InetAddress ip = InetAddress.getByName(host);
return new Socket(ip, port);
}
catch (UnknownHostException e)
{
System.err.println("The host is unknown.");
}
catch (IOException e)
{
System.err.println("Network error.");
}
}
}
I tried connecting on localhost, and it worked. Then i tried connecting with my friend on a remote computer using the ip address as the network name and it did not work giving an exception. What name do i use to connect to a remote server.
You need to give your friend your remote IP address.
I use this method in a loop to get the host name of 4 terminal in my local network identified by the ip address terminal[i].getIp() .
try {
// Get hostname by textual representation of IP address
InetAddress addr = InetAddress.getByName(terminal[i].getIp());
// Get the host name
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
the problem here its that code take so long to return the result (up to 5 seconds)
I wonder if there is another more optimized method.
Try the library from Google Guava, I think there are more optimized
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/net/InetAddresses.html