如何使用 Kotlin 使用协程扫描本地 IP 地址
我有一个应用程序可以扫描本地 IP 地址以连接到开放端口 8102。我已经能够获取正确的 IP 地址,但需要很长时间,因为每次轮询的超时时间为 200 毫秒。这是我成功达到的最低水平。
我想我的问题是有没有办法使用协程来分割工作并更快地获取地址?现在大约需要 3 秒,而我的目标地址仅为 192.168.0.21。
这是我的代码:
fun init() = GlobalScope.launch(Dispatchers.IO) {
//Get local ip
DatagramSocket().use { socket ->
socket.connect(InetAddress.getByName("8.8.8.8"), 10002)
ip = socket.getLocalAddress().getHostAddress().split(".") as MutableList<String>
}
//Go through local addresses to find receiver
txtOutput.text = ip.toString()
prefix = ip[0] + "." + ip[1] + "." + ip[2] + "."
var i = 1
do {
try {
client = Socket()
client.connect(InetSocketAddress(prefix + i.toString(), 8102), 200)
} catch (e: Exception) {
print(e.toString())
i++
}
} while (!(client.isConnected) or (i > 254))
targetIP = prefix + i.toString()
client = Socket()
try{
client.connect(InetSocketAddress(targetIP, 8102), 150)
if(client.isConnected){
client.keepAlive = true}}
catch (e:IOException){
cancel("Could not connect")
}
I have an app that scans local IP addresses to connect to open port 8102. I've been able to get the correct IP address, but it takes a long time because each poll has a timeout of 200 milliseconds. That's the lowest I've been able to get it with success.
I guess my question is is there a way to use coroutines to split up the work and get the address sooner? Right now it's taking about 3 seconds and the address I'm targeting is only 192.168.0.21.
Here's my code:
fun init() = GlobalScope.launch(Dispatchers.IO) {
//Get local ip
DatagramSocket().use { socket ->
socket.connect(InetAddress.getByName("8.8.8.8"), 10002)
ip = socket.getLocalAddress().getHostAddress().split(".") as MutableList<String>
}
//Go through local addresses to find receiver
txtOutput.text = ip.toString()
prefix = ip[0] + "." + ip[1] + "." + ip[2] + "."
var i = 1
do {
try {
client = Socket()
client.connect(InetSocketAddress(prefix + i.toString(), 8102), 200)
} catch (e: Exception) {
print(e.toString())
i++
}
} while (!(client.isConnected) or (i > 254))
targetIP = prefix + i.toString()
client = Socket()
try{
client.connect(InetSocketAddress(targetIP, 8102), 150)
if(client.isConnected){
client.keepAlive = true}}
catch (e:IOException){
cancel("Could not connect")
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理论上是可以的,但是需要测试一下
It is theoretically possible but you have to test it