2015년 10월 19일 월요일

PING을 통해서 네트워크 연결 상태 체크하기 - 안드로이드 소스 코드에서





ping을 통해서 네트워크 연결 상태 체크하기 - 안드로이드 소스 코드에서

Runtime runTime = Runtime.getRuntime();

String host = "192.168.0.13";
String cmd = "ping -c 1 -W 10 "+host; //-c 1은 반복 횟수를 1번만 날린다는 뜻
Process proc = null;

try {
proc = runTime.exec(cmd);
} catch(IOException ie){
Log.d("runtime.exec()", ie.getMessage());
}

try {
proc.waitFor();
} catch(InterruptedException ie){
Log.d("proc.waitFor", ie.getMessage());
}

//여기서 반환되는 ping 테스트의 결과 값은 0, 1, 2 중 하나이다.
// 0 : 성공, 1 : fail, 2 : error이다.
int result = proc.exitValue();

if (result == 0) {
Log.d("ping test 결과", "네트워크 연결 상태 양호");
} else {
Log.d("ping test 결과", "연결되어 있지 않습니다.");
}


※ ping 명령어 옵션들

-4, -6 Force IPv4 or IPv6 hostname resolution
-c CNT Send only CNT pings
-s SIZE Send SIZE data bytes in packets (default=56)
-I iface/IP Use interface or IP address as source
-W timeout Seconds to wait for the first response (default:10)
                 (after all -c CNT packets are sent)
-w deadline Seconds until ping exits (default:infinite)
                 (can exit earlier with -c CNT)
-q               Quiet, only displays output at start and when finished

안드로이드의 기반이 리눅스이기 때문에 DOS에서의 ping 명령어 옵션과는 약간의 차이가 있다.

-c 옵션은 ping을 날릴 횟수이다.
-W 옵션은 ping을 날린 이후 리턴 결과를 기다릴 timeout 시간 값이다. 연결 상태가 끊겼거나 연결 상태가 좋지 않을때 이 대기 시간 동안 응답이 없으면 연결 실패로 간주한다.

위의 옵션들은 대소문자를 구분한다.
따라서 ping -C xxx.xxx.x.x는 잘못된 사용법이다.

댓글 없음:

댓글 쓰기