I have written a small application in Kotlin which sends a Magic Packet to a smart tv over my local network. I used this approach (code), rewritten in Kotlin (plus i hardcoded the IP and MAC for testing purposes).
When the tv is shutdown, i can easily restart it with my application. After a while, that doesn't work anymore.
Code
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
fun main() {
magicPacket("A8:23-FE:A0:5C:DB", "192.168.xx.xxx", 7)
}
/**
* Android:
* Network interaction starting in new Thread!
*/
fun magicPacket(mac: String, ip: String, PORT: Int = 7) {
// throws IllegalThreadStateException without declaration
//val t = thread {
val packet = buildPacket(mac)
val datagramSocket = DatagramSocket()
try {
datagramSocket.send(
DatagramPacket(
packet,
packet.size,
InetAddress.getByName(ip),
PORT
)
)
datagramSocket.close()
} catch (e: Exception) {
e.printStackTrace()
}
//}
}
private fun buildPacket(mac: String): ByteArray {
// prepare packet (6 bytes header) (16 * 6 bytes MAC)
val temp = ByteArray(6 + 6 * 16)
val macBytes = ByteArray(6)
for (i in 0..5) {
temp[i] = 0xFF.toByte()
macBytes[i] = mac.split(":", "-")[i].toInt(16).toByte()
}
for (i in 6 until temp.size step macBytes.size) System.arraycopy(
macBytes,
0,
temp,
i,
macBytes.size
)
return temp
}
What i tried in code
- i changed port numbers (starting with random (11111, 55555, quick google search suggested ports 0, 7, 9) which all failed
- sending not one but 10 to 100 packets
- i ran the app as a java (kotlin) project from Intellij on my PC aswell, same results
What i found out yet
- WOL doesn't work on every device
- power states may be important
- Wake On Lan manages to wake up the device no matter what, so i think the problem is the app, not any settings
- All network IPs and MACs are static