Проверка подключения интернета java

How to check if internet connection is present in Java?

But is there something more appropriate to perform that task, especially if you need to do consecutive checks very often and a loss of internet connection is highly probable?

The answer to this is the same as to mamy other questions of the same form. The only proper way to determine whether any resource is available is to try to use it, in the normal course of execution, and cope with failure as and when it happens. Any other technique is one form or another of trying to predict the future.

18 Answers 18

You should connect to the place that your actual application needs. Otherwise you’re testing whether you have a connection to somewhere irrelevant (Google in this case).

In particular, if you’re trying to talk to a web service, and if you’re in control of the web service, it would be a good idea to have some sort of cheap «get the status» web method. That way you have a much better idea of whether your «real» call is likely to work.

In other cases, just opening a connection to a port that should be open may be enough — or sending a ping. InetAddress.isReachable may well be an appropriate API for your needs here.

what if you connect to a resource you want to communicate with and it fails. how do you know that it was the problem of the target server and not bcs there was no internet connection? so ‘connect to the place that your actual application needs’ is not really a solution that would not be a reliable check

@Chris: It depends whether you really care what the problem is. I agree that you can get more diagnostic information if (after a failure) you then connect somewhere else as well. But the most important piece of information is surely «Can I use the resource I’m trying to use?»

@Pacerier: There are lots of different things that could go wrong, and diagnosing where there’s a problem is a tricky matter. What if you hadn’t done anything, but your ISP’s pipe to the rest of the world had gone down? Then you might still have a perfectly valid router connection etc — and you might even be able to get to your ISP’s domain — but wouldn’t be able to reach other sites. All I’m saying is that «Is my internet up?» doesn’t make sense as a question, really — not in precise terms. What are you proposing the test should be?

Читайте также:  После подключение интернета вылетает

@Pacerier: So you’d try several web sites which are normally up. You’d also want to check whether DNS resolution is working — and indeed whether facebook.com could even be resolved. Then there’s the possibility that Facebook is down for a large proportion of users (e.g. traffic for one country is going to one data centre which is having problems) without the site being completely down.

The code you basically provided, plus a call to connect should be sufficient. So yeah, it could be that just Google’s not available but some other site you need to contact is on but how likely is that? Also, this code should only execute when you actually fail to access your external resource (in a catch block to try and figure out what the cause of the failure was) so I’d say that if both your external resource of interest and Google are not available chances are you have a net connectivity problem.

private static boolean netIsAvailable() < try < final URL url = new URL("http://www.google.com"); final URLConnection conn = url.openConnection(); conn.connect(); conn.getInputStream().close(); return true; >catch (MalformedURLException e) < throw new RuntimeException(e); >catch (IOException e) < return false; >> 

This works but takes a while till it returns false . Any faster solution? Cmd immediately tells me that the host couldn’t be found when I try to ping it.

People have suggested using INetAddress.isReachable. The problem is that some sites configure their firewalls to block ICMP Ping messages. So a «ping» might fail even though the web service is accessible.

And of course, the reverse is true as well. A host may respond to a ping even though the webserver is down.

And of course, a machine may be unable to connect directly to certain (or all) web servers due to local firewall restrictions.

The fundamental problem is that «can connect to the internet» is an ill-defined question, and this kind of thing is difficult to test without:

  1. information on the user’s machine and «local» networking environment, and
  2. information on what the app needs to access.

So generally, the simplest solution is for an app to just try to access whatever it needs to access, and fall back on human intelligence to do the diagnosis.

Источник

Как правильно проверить наличие подключения к интернету?

Вроде бы работает, но проблема в том что таймаут не срабатывает. Если сайт, к которому идет обращение, висит, то коннект обрывается только через дефолтные 20 секунд. Получается что приложение зависает на 20 сек. Подскажите, как правильно установить таймаут? Возможно есть какой-то другой способ проверки подключения, чтобы обойти проблему таймаута?

1 ответ 1

Проверить наличие соединения с интернетом — просто протестировать загружается ли какой-либо сайт или нет (можно какой-нибудь сервис WhoIs или Google)

Читайте также:  Blackview настроить мобильный интернет

В любом случае для проверки лучше всего использовать крупные сайты, например http://ru.stackoverflow.com или google.com. Либо проверять последовательно доступность нескольких сайтов — если хоть один из них доступен — значит соединение с интернетом присутствует.

private static boolean checkInternetConnection() < Boolean result = false; HttpURLConnection con = null; try < con = (HttpURLConnection) new URL("http://ru.stackoverflow.com/").openConnection(); con.setRequestMethod("HEAD"); result = (con.getResponseCode() == HttpURLConnection.HTTP_OK); >catch (Exception e) < e.printStackTrace(); >finally < if (con != null) < try < con.disconnect(); >catch (Exception e) < e.printStackTrace(); >> > return result; > 

(метод isReachable(), должен проверять хост в интернете на доступность)

(способ заточенный под Windows. Основан на использовании ping)

а вообще. ЗАЧЕМ ТАКАЯ ПРОВЕРКА ВООБЩЕ НУЖНА?

Вам нужен ответ от какого-то ресурса (ведь вы хотите куда-то обратиться) — попытайтесь обратиться сразу, без проверок доступности интернета. Если в ходе подключения появится ошибка — обработайте ее через try, выведите сообщение:

«Пардон, пацаны, интернет не подключен!»

Источник

How to check internet connectivity in Java [duplicate]

I am working on a Java project which needs to have an internet connection at all times. I want my program to keep checking the internet connection at some time intervals (say 5 or 10 seconds) and display a message as soon as no internet connection is detected. I have tried to use the isReachable method to achieve this functionality, below is the code —

try < InetAddress add = InetAddress.getByName("www.google.com"); if(add.isReachable(3000)) System.out.println("Yes"); else System.out.println("No"); >catch (UnknownHostException e) < System.out.println("unkownhostexception"); >catch (IOException e)

Thanks but the solution offered there, does not work in my case. the author too said its just a hack may not work in some cases.

2 Answers 2

I agree with Raffaele’s suggestion if you just need to use the internet frequently. Just try to do it, and be prepared to handle the exceptions when it fails.

If you need to monitor the availability of the internet for some reason, even when you don’t intend to use it yet and don’t know who you’ll connect to, just try a connection to a known-good site (google.com, amazon.com, baidu.com. ).

This will work to test a few sites:

public static void main(String[] args) < System.out.println( "Online: " + (testInet("myownsite.example.com") || testInet("google.com") || testInet("amazon.com")) ); >public static boolean testInet(String site) < Socket sock = new Socket(); InetSocketAddress addr = new InetSocketAddress(site,80); try < sock.connect(addr,3000); return true; >catch (IOException e) < return false; >finally < try catch (IOException e) <> > > 

I think this can be used for better error reporting. First you try accessing the service, but if it fails you can then check availability of other sites. This allows delivering a more meaningful error message to the user. Either «the remote service is currently unreachable» or «you currently have no internet connection».

The only way I am aware of is sending a packet to some known host, known in the sense that you know it will always be up and running and reachable from the calling site.

Читайте также:  Нет интернета ошибка 103

However, for example, if you choose a named host, the ping may fail due to a DNS lookup failure.

I think you shouldn’t worry about this problem: if your program needs an Internet connection, it’s because it sends or receives data. Connections are not a continuous concept like a river, but are more like a road. So just use the Java standard for dealing with connection errors: IOExceptiions. When your program must send data, the underlying API will certailnly throw an IOE in the case the network is down. If your program expects data, instead, use a timeout or something like that to detect possible errors in the network stack and report it to the user.

Источник

Detect internet Connection using Java [duplicate]

I want to see if anyone has an easy way of detecting if there is an internet connection when using Java. The current app used the «InternetGetConnectedState» method in the WinInit DLL for windows, but my app needs to be cross-platform for mac operation and this way will not work. I do not know JNI at all either to use DLLs in Java and it became frustrating fast. Only ways I could think of were tring to open a URL connection to a website and if that fails, return false. My other way is below, but I didn’t know if this was generally stable. If I unplug my network cable i do get an UnknownHostException when trying to create the InetAddress. Otherwise if the cable is connected I get a valid InetAddress object. I didnt test the below code on a mac yet. Thanks for any examples or advice you can provide. UPDATE: Final code block is at the bottom. I decided to take the advice of an HTTP request (in this case Google). Its simple and sends a request to the site for data to be returned. If I cannot get any content from the connection, there is no internet.

public static boolean isInternetReachable() < try < InetAddress address = InetAddress.getByName("java.sun.com"); if(address == null) < return false; >> catch (UnknownHostException e) < // TODO Auto-generated catch block e.printStackTrace(); return false; >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); return false; >return true; > 
//checks for connection to the internet through dummy request public static boolean isInternetReachable() < try < //make a URL to a known source URL url = new URL("http://www.google.com"); //open a connection to that source HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection(); //trying to retrieve data from the source. If there //is no connection, this line will fail Object objData = urlConnect.getContent(); >catch (UnknownHostException e) < // TODO Auto-generated catch block e.printStackTrace(); return false; >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); return false; >return true; > 

Источник

Оцените статью
Adblock
detector