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.

Источник

Причины и решения проблемы: почему Java не видит интернет

Java является одним из самых популярных и широко используемых языков программирования в мире. Однако иногда разработчики сталкиваются с проблемой, когда Java приложение не может получить доступ к интернету. В этой статье мы рассмотрим возможные причины такой проблемы и предложим решения.

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

Причины проблемы

1. Проблемы с сетевым подключением

Одна из основных причин, по которой Java не видит интернет, может быть связана с проблемами с сетевым подключением. Это может быть обусловлено отключением сетевого кабеля или проблемами с Wi-Fi. Проверьте, что сетевое подключение на компьютере работает правильно.

2. Неправильная настройка прокси-сервера

Если ваша сеть использует прокси-сервер для доступа в интернет, неправильная настройка прокси-сервера в Java может привести к проблеме отсутствия соединения. Проверьте настройки прокси-сервера и убедитесь, что они правильно заданы в вашем Java приложении.

3. Брандмауэр или антивирусное программное обеспечение

Некоторые брандмауэры или антивирусные программы могут блокировать соединение между Java приложением и интернетом. Убедитесь, что ваш брандмауэр или антивирусное программное обеспечение не блокируют доступ Java к интернету. Если установлено блокирование, настройте программы для разрешения соединения Java с интернетом.

4. Отсутствие необходимых разрешений

Java приложение может не иметь необходимых разрешений для доступа к интернету. Проверьте, что ваше приложение имеет соответствующие разрешения для доступа в интернет.

Решения проблемы

1. Проверьте сетевое подключение

Убедитесь, что ваш компьютер имеет рабочее сетевое подключение. Проверьте физическое подключение кабеля или убедитесь, что Wi-Fi работает правильно. Попробуйте открыть веб-страницу в браузере, чтобы убедиться, что интернет-соединение работает.

2. Проверьте настройки прокси-сервера

Если ваша сеть использует прокси-сервер, убедитесь, что настройки прокси-сервера в Java приложении правильны. Обратитесь к администратору вашей сети, чтобы узнать правильные настройки прокси-сервера.

3. Проверьте наличие блокировок

Проверьте, нет ли блокировок со стороны брандмауэра или антивирусного программного обеспечения. Добавьте Java приложение в список исключений или временно отключите брандмауэр или антивирусное программное обеспечение для проверки доступа к интернету.

4. Проверьте разрешения

Если Java приложение не имеет необходимых разрешений для доступа к интернету, убедитесь, что вы предоставили соответствующие разрешения. Это может быть сделано путем настройки файловой системы разрешений приложения или использования политик безопасности Java.

Заключение

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

Источник

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

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

1 ответ 1

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

В любом случае для проверки лучше всего использовать крупные сайты, например 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, выведите сообщение:

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

Источник

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