투케이2K

516. (kotlin/코틀린) [유틸 파일] getDomainIpList : 도메인 입력해 접속 가능한 IP 주소 확인 본문

Kotlin

516. (kotlin/코틀린) [유틸 파일] getDomainIpList : 도메인 입력해 접속 가능한 IP 주소 확인

투케이2K 2024. 8. 2. 19:27
반응형

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Kotlin

 

[소스 코드]

        // -----------------------------------------------------------------------------------------
        // TODO [SEARCH FAST] : [Observable] : getDomainIpList : 도메인 입력해 접속 가능한 IP 주소 확인
        // -----------------------------------------------------------------------------------------
        // TODO [호출 방법 소스 코드]
        // -----------------------------------------------------------------------------------------
        /*
        try {

            C_App.getDomainIpList(A_Intro@this, "www.google.com", 80, 2000)
                .subscribeOn(AndroidSchedulers.mainThread()) // [Observable (생성자) 로직을 IO 스레드에서 실행 : 백그라운드]
                .observeOn(Schedulers.io()) // [Observer (관찰자) 로직을 메인 스레드에서 실행]
                .subscribe(
                    { value ->
                        S_Log._W_("도메인 IP 정보 확인 :: onNext :: $value", null)
                    },
                    { error ->
                        S_Log._E_("도메인 IP 정보 확인 :: onError :: " + error.message.toString(), null)
                    }
                )
                {
                }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        */
        // -----------------------------------------------------------------------------------------
        fun getDomainIpList(mContext: Context, domain: String, port: Int, milliSecond: Int): Observable<ArrayList<Map<String, String>>> {

            // [로직 처리 실시]
            return Observable.create { subscriber: ObservableEmitter<ArrayList<Map<String, String>>> ->

                /**
                 * // -----------------------------------------
                 * [getDomainIpList 메소드 설명]
                 * // -----------------------------------------
                 * 1. 도메인 입력해 접속 가능한 IP 주소 확인 (nslookup 도메인)
                 * // -----------------------------------------
                 * 2. 리턴 데이터 :
                 *
                 * [{ConnectStatus=Success, HostAddress=2404:6800:400a:813::2004}, {ConnectStatus=Success, HostAddress=142.250.207.100}]
                 * // -----------------------------------------
                 * 3. 참고 :
                 *
                 * ipV4 주소인 경우 제한적이므로 특정 통신사 마다 주기적으로 변경 될 수 있음
                 *
                 * http 기본 포트 : 80
                 *
                 * // -----------------------------------------
                 */

                S_Log._D_("도메인 입력해 접속 가능한 IP 주소 확인", arrayOf(
                    "domain :: $domain",
                    "port :: $port",
                    "milliSecond :: $milliSecond"
                ))

                try {

                    // [인풋 데이터 방어 로직 작성]
                    if (C_Util.stringNotNull(domain) === true && domain.contains(".") == true && port >= 0 && milliSecond >= 0) {

                        // [도메인 https , http 시작 확인 및 제거]
                        var address = domain.trim { it <= ' ' }
                        address = address.replace("http://".toRegex(), "")
                        address = address.replace("https://".toRegex(), "")


                        // [AsyncTask] : [IP 정보 확인 및 연결 여부 테스트 수행]
                        val finalAddress = address
                        AsyncTask.execute {

                            val resultList = ArrayList<Map<String, String>>()

                            try {

                                val addressAll = InetAddress.getAllByName(finalAddress)

                                for (adr in addressAll) {
                                    //S_Log._D_("Connection Test [Start] :: " + String.valueOf(adr.getHostAddress()), null);
                                    try {
                                        Socket().connect(InetSocketAddress(adr, port), milliSecond) // TODO [HTTP : 기본 80 포트 / 특정 포트 지정]

                                        S_Log._W_("Connection Test [Success] :: " + adr.hostAddress.toString(), null)

                                        val map: MutableMap<String, String> = HashMap()
                                        map["HostAddress"] = adr.hostAddress.toString()
                                        map["ConnectStatus"] = "Success"

                                        resultList.add(map)

                                    } catch (e: Exception) {
                                        S_Log._E_("Connection Test [Fail] :: " + adr.hostAddress.toString(), null)

                                        val map: MutableMap<String, String> = HashMap()
                                        map["HostAddress"] = adr.hostAddress.toString()
                                        map["ConnectStatus"] = "Fail"

                                        resultList.add(map)
                                    }
                                }

                            } catch (e: Exception) {
                                e.printStackTrace()

                                if (resultList != null && resultList.size > 0) {
                                    resultList.clear()
                                }

                            } finally {
                                subscriber.onNext(resultList)
                                subscriber.onComplete()
                            }
                        }

                    } else {
                        try { subscriber.onError(Throwable("[Error] : Input Data Is Null")) } catch (ex: Exception) { ex.printStackTrace() }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                    try { subscriber.onError(Throwable("[Exception] : [catch] : $e")) } catch (ex: Exception) { ex.printStackTrace() }
                }
            }
        }
 

[결과 출력]

 

W///===========//: ================================================
I/: [LOG :: CLASS PLACE :: com.example.kotlinproject.A_Intro$1$1.onNext(A_Intro.java:344)]
I/: ----------------------------------------------------
I/: [LOG :: NOW TIME :: 2024-08-02 13:45:03 금요일]
I/: ----------------------------------------------------
I/: [LOG :: DESCRIPTION :: 도메인 IP 정보 확인 :: onNext :: [{ConnectStatus=Success, HostAddress=2404:6800:400a:813::2004}, {ConnectStatus=Success, HostAddress=142.250.207.100}]]
W///===========//: ================================================

 

반응형
Comments