Adjusting the default listening port for hy2

This commit is contained in:
2dust
2024-09-30 13:31:10 +08:00
parent e073b19343
commit de22e16cd4
4 changed files with 17 additions and 7 deletions

View File

@@ -164,7 +164,7 @@ object V2RayServiceManager {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_SUCCESS, "")
showNotification()
PluginUtil.runPlugin(service, config)
PluginUtil.runPlugin(service, config, result.domainPort)
} else {
MessageUtil.sendMsg2UI(service, AppConfig.MSG_STATE_START_FAILURE, "")
cancelNotification()

View File

@@ -4,11 +4,9 @@ import android.content.Context
import android.os.SystemClock
import android.util.Log
import com.google.gson.Gson
import com.v2ray.ang.AppConfig
import com.v2ray.ang.AppConfig.ANG_PACKAGE
import com.v2ray.ang.dto.EConfigType
import com.v2ray.ang.dto.ServerConfig
import com.v2ray.ang.util.MmkvManager.settingsStorage
import com.v2ray.ang.util.fmt.Hysteria2Fmt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -25,14 +23,15 @@ object PluginUtil {
// return PluginManager.init(name)!!
// }
fun runPlugin(context: Context, config: ServerConfig?) {
fun runPlugin(context: Context, config: ServerConfig?, domainPort: String?) {
Log.d(packageName, "runPlugin")
val outbound = config?.getProxyOutbound() ?: return
if (outbound.protocol.equals(EConfigType.HYSTERIA2.name, true)) {
Log.d(packageName, "runPlugin $HYSTERIA2")
val socksPort = 100 + SettingsManager.getSocksPort()
val socksPort = domainPort?.split(":")?.last()
.let { if (it.isNullOrEmpty()) return else it.toInt() }
val hy2Config = Hysteria2Fmt.toNativeConfig(config, socksPort) ?: return
val configFile = File(context.noBackupFilesDir, "hy2_${SystemClock.elapsedRealtime()}.json")

View File

@@ -453,6 +453,17 @@ object Utils {
}
}
fun findFreePort(ports: List<Int>): Int {
for (port in ports) {
try {
return ServerSocket(port).use { it.localPort }
} catch (ex: IOException) {
continue // try next port
}
}
// if the program gets here, no port in the range was found
throw IOException("no free port found")
}
}

View File

@@ -143,7 +143,7 @@ object V2rayConfigUtil {
private fun outbounds(v2rayConfig: V2rayConfig, outbound: V2rayConfig.OutboundBean, isPlugin: Boolean): Pair<Boolean, String> {
if (isPlugin) {
val socksPort = 100 + SettingsManager.getSocksPort()
val socksPort = Utils.findFreePort(listOf(100 + SettingsManager.getSocksPort(), 0))
val outboundNew = V2rayConfig.OutboundBean(
mux = null,
protocol = EConfigType.SOCKS.name.lowercase(),