rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

jcifs-ng SMBサーバーへの接続の成否確認

2021 Sep. 17.

SmbFile#list()で例外が発生するかどうかで確認できる。

接続先パスがファイルでもディレクトリでも同じように動作した。
SmbFileのコンストラクト時に接続成否を把握できなかった。

サンプルkotlin androidコード

    fun connectSmb(): Boolean {
        try {
            val prop = Properties()  // java.util.Properties
            prop.setProperty("jcifs.smb.client.minVersion", "SMB202")
            prop.setProperty("jcifs.smb.client.maxVersion", "SMB300")
            val baseCxt = BaseContext(PropertyConfiguration(prop))
            val auth =
                baseCxt.withCredentials(NtlmPasswordAuthenticator(domain, user, password))

            // connect to SMB server
            smb = SmbFile(smbUrl, auth)
            Log.d("MyApp", "List: "+ smb.list())  // <- Checking the result of SMB connection here
        } catch (e: Exception) {
            Log.d("MyApp", "1: " + e.toString())
            try {
                smb.close()
            }
            catch (e: java.lang.Exception) {
                Log.d("MyApp", "2: " + e.toString())
                return false
            }
            return false
        }
        Log.d("MyApp", "Finished to connect SMB function")
        return true
    }


SMBサーバーへの接続に失敗した時の出力例

D/MyApp: 1: jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.