code

Java에 인터넷 연결이 있는지 확인하는 방법은 무엇입니까?

codestyles 2020. 12. 15. 19:20
반응형

Java에 인터넷 연결이 있는지 확인하는 방법은 무엇입니까?


자바를 통해 인터넷에 연결할 수 있는지 어떻게 확인합니까? 한 가지 방법은 다음과 같습니다.

final URL url = new URL("http://www.google.com");
final URLConnection conn = url.openConnection();
... if we got here, we should have net ...

하지만 뭔가가 그 작업을 수행하는 것이 더 적절하다 특히 당신이해야 할 경우 연속 검사를 자주하고 인터넷 연결의 손실 가능성이 매우 높다?


실제 응용 프로그램에 필요한 위치에 연결해야합니다. 그렇지 않으면 관련없는 곳 (이 경우 Google)에 연결되어 있는지 테스트합니다.

특히 웹 서비스와 대화를 시도하고 웹 서비스를 제어하는 ​​경우 저렴한 "상태 가져 오기"웹 메소드를 사용하는 것이 좋습니다. 이렇게하면 "실제"전화가 효과가 있는지 여부를 훨씬 더 잘 알 수 있습니다.

다른 경우에는 열려 있어야하는 포트에 대한 연결을 여는 것만으로도 충분하거나 핑을 보낼 수 있습니다. InetAddress.isReachable여기에서 귀하의 요구에 적합한 API가 될 수 있습니다.


기본적으로 제공 한 코드와 호출로 connect충분합니다. 예, Google을 사용할 수 없지만 연락해야하는 다른 사이트가있을 수 있지만 그 가능성은 얼마나됩니까? 또한이 코드는 실제로 외부 리소스에 액세스하지 못할 때만 실행되어야합니다 ( catch실패의 원인을 파악하기 위해 블록에서). 따라서 관심있는 외부 리소스 Google이 모두 그렇지 않은 경우 가능한 기회는 네트워크 연결 문제가 있습니다.

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;
    }
}

사람들은 INetAddress.isReachable 사용을 제안했습니다. 문제는 일부 사이트에서 ICMP Ping 메시지를 차단하도록 방화벽을 구성한다는 것입니다. 따라서 웹 서비스에 액세스 할 수 있어도 "ping"이 실패 할 수 있습니다.

물론 그 반대도 마찬가지입니다. 웹 서버가 다운 된 경우에도 호스트가 ping에 응답 할 수 있습니다.

물론 컴퓨터는 로컬 방화벽 제한으로 인해 특정 (또는 모든) 웹 서버에 직접 연결할 수 없습니다.

근본적인 문제는 "인터넷에 연결할 수 있음"이 잘못 정의 된 질문이며 다음과 같은 문제 없이는 테스트하기가 어렵다는 것입니다.

  1. 사용자의 컴퓨터 및 "로컬"네트워킹 환경에 대한 정보
  2. 앱이 액세스해야하는 항목에 대한 정보.

따라서 일반적으로 가장 간단한 솔루션은 앱이 액세스해야하는 모든 것에 액세스하고 진단을 수행하기 위해 인간 지능에 의존하는 것입니다.


Java 6을 사용하는 경우 NetworkInterface사용하여 사용 가능한 네트워크 인터페이스를 확인할 수 있습니다. 예를 들면 다음과 같습니다.

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
  NetworkInterface interf = interfaces.nextElement();
  if (interf.isUp() && !interf.isLoopback())
    return true;
}

아직 직접 시도하지 않았습니다.


이 코드 :

"127.0.0.1".equals(InetAddress.getLocalHost().getHostAddress().toString());

반환-나에게- true오프라인이면 false, 그렇지 않으면. (글쎄, 이것이 모든 컴퓨터에 해당하는지 모르겠습니다).

이것은 여기에있는 다른 접근 방식보다 훨씬 빠르게 작동합니다.


편집 : "플립 스위치"(랩톱의 경우) 또는 인터넷 연결을위한 다른 시스템 정의 옵션이 꺼져있는 경우에만 작동하는 것을 발견했습니다. 즉, 시스템 자체는 IP 주소를 찾지 않는 것을 알고 있습니다.


이 코드는 작업을 안정적으로 수행해야합니다.

try-with-resources을 사용할 때 리소스를 닫을 필요가 없습니다.

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class InternetAvailabilityChecker
{
    public static boolean isInternetAvailable() throws IOException
    {
        return isHostAvailable("google.com") || isHostAvailable("amazon.com")
                || isHostAvailable("facebook.com")|| isHostAvailable("apple.com");
    }

    private static boolean isHostAvailable(String hostName) throws IOException
    {
        try(Socket socket = new Socket())
        {
            int port = 80;
            InetSocketAddress socketAddress = new InetSocketAddress(hostName, port);
            socket.connect(socketAddress, 3000);

            return true;
        }
        catch(UnknownHostException unknownHost)
        {
            return false;
        }
    }
}

나는 보통 그것을 세 단계로 나눕니다.

  1. 먼저 도메인 이름을 IP 주소로 확인할 수 있는지 확인합니다.
  2. 그런 다음 TCP (포트 80 및 / 또는 443)를 통해 연결을 시도하고 정상적으로 닫습니다.
  3. 마지막으로 HTTP 요청을 발행하고 200 개의 응답을 확인합니다.

어느 시점에서든 실패하면 사용자에게 적절한 오류 메시지를 제공합니다.


URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();

/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */

/* Get input stream */
con.getInputStream();

위의 명령문을 try catch 블록에 넣고 예외가 catch되면 인터넷 연결이 설정되지 않았 음을 의미합니다. :-)


NetworkInterface를 사용하여 네트워크를 기다리는 코드는 고정 네트워크 주소에서 DHCP로 전환 할 때까지 저에게 효과적이었습니다. 약간의 향상으로 DHCP에서도 작동합니다.

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
    NetworkInterface interf = interfaces.nextElement();
    if (interf.isUp() && !interf.isLoopback()) {
    List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
    for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
        InterfaceAddress adr = iter.next();
        InetAddress inadr = adr.getAddress();
        if (inadr instanceof Inet4Address) return true;
            }
    }
}

이것은 IPv4 네트워크 용 openSuse 13.1의 Java 7에서 작동합니다. 원래 코드의 문제는 일시 중단에서 다시 시작한 후 인터페이스가 작동했지만 IPv4 네트워크 주소가 아직 할당되지 않았다는 것입니다. 이 할당을 기다린 후 프로그램은 서버에 연결할 수 있습니다. 하지만 IPv6의 경우 어떻게 해야할지 모르겠습니다.


InetAddress.isReachable 인터넷에 연결되어 있으면 때때로 false를 반환합니다.

Java에서 인터넷 가용성을 확인하는 다른 방법은 다음과 같습니다.이 함수는 실제 ICMP ECHO핑을 수행합니다.

public static boolean isReachableByPing(String host) {
     try{
                String cmd = "";
                if(System.getProperty("os.name").startsWith("Windows")) {   
                        // For Windows
                        cmd = "ping -n 1 " + host;
                } else {
                        // For Linux and OSX
                        cmd = "ping -c 1 " + host;
                }

                Process myProcess = Runtime.getRuntime().exec(cmd);
                myProcess.waitFor();

                if(myProcess.exitValue() == 0) {

                        return true;
                } else {

                        return false;
                }

        } catch( Exception e ) {

                e.printStackTrace();
                return false;
        }
}

1) 애플리케이션이 연결되어야하는 위치를 파악합니다.

2) 작업자 프로세스를 설정하여 InetAddress.isReachable확인 하여 해당 주소에 대한 연결을 모니터링합니다.


This code is contained within a jUnit test class I use to test if a connection is available. I always receive a connection, but if you check the content length it should be -1 if not known :

  try {
    URL url = new URL("http://www.google.com");
    URLConnection connection = url.openConnection();

    if(connection.getContentLength() == -1){
          fail("Failed to verify connection");
    }
  } 
  catch (IOException e) {
      fail("Failed to open a connection");
      e.printStackTrace();
  }

public boolean checkInternetConnection()
{
     boolean status = false;
     Socket sock = new Socket();
     InetSocketAddress address = new InetSocketAddress("www.google.com", 80);

     try
     {
        sock.connect(address, 3000);
        if(sock.isConnected()) status = true;
     }
     catch(Exception e)
     {
         status = false;       
     }
     finally
     {
        try
         {
            sock.close();
         }
         catch(Exception e){}
     }

     return status;
}

There is also a gradle option --offline which maybe results in the behavior you want.


The following piece of code allows us to get the status of the network on our Android device

public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            TextView mtv=findViewById(R.id.textv);
            ConnectivityManager connectivityManager=
                  (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if(((Network)connectivityManager.getActiveNetwork())!=null)
                    mtv.setText("true");
                else
                    mtv.setText("fasle");
            }
        }
    }

ReferenceURL : https://stackoverflow.com/questions/1402005/how-to-check-if-internet-connection-is-present-in-java

반응형