-
-
Save md-5/3390780 to your computer and use it in GitHub Desktop.
package com.md_5; | |
import java.io.IOException; | |
import java.net.DatagramPacket; | |
import java.net.DatagramSocket; | |
import java.net.InetSocketAddress; | |
import java.util.logging.Level; | |
import org.bukkit.plugin.java.JavaPlugin; | |
public class LanBukkit extends JavaPlugin implements Runnable { | |
private DatagramSocket socket; | |
private InetSocketAddress broadcastAddr = new InetSocketAddress("224.0.2.60", 4445); | |
@Override | |
public void onEnable() { | |
try { | |
socket = new DatagramSocket(); | |
getServer().getScheduler().scheduleAsyncRepeatingTask(this, this, 0, 30); | |
} catch (IOException ex) { | |
getLogger().severe("Could not start LAN server broadcaster"); | |
} | |
} | |
@Override | |
public void onDisable() { | |
if (socket != null) { | |
socket.close(); | |
} | |
getServer().getScheduler().cancelTasks(this); | |
} | |
public void run() { | |
try { | |
byte[] broadcast = ("[MOTD]" + getServer().getMotd() + "[/MOTD][AD]" + getServer().getIp() + ":" + getServer().getPort() + "[/AD]").getBytes(); | |
socket.send(new DatagramPacket(broadcast, broadcast.length, broadcastAddr)); | |
} catch (IOException ex) { | |
getLogger().log(Level.SEVERE, "Caught exception, shutting down", ex); | |
} | |
} | |
} |
getServer().getIp() only gets the bound IP specified in server.properties; would be nice if this automagically detected your local IP.
Thanks for letting me know, I will add that, gist doesnt seem to give me alerts.
Try: byte[] broadcast = ("[MOTD]" + getServer().getMotd() + "[/MOTD][AD]" + InetAddress.getLocalHost() + ":" + getServer().getPort() + "[/AD]").getBytes();
That's what Minecraft itself uses pretty much and what I use in my slightly modified version, but thanks again.
For certain linux machines, InetAddress.getLocalHost() does not work and generates an error. For my implementation, I just put a question mark (or other invalid host name), and it works correctly to get the IP address.
Also, line 13 should have a broadcast IP address, I just use 255.255.255.255 for simplicity (for some reason I was unable to get broadcasts without it...).
Other than that, it seems to work flawlessly!
where do you put this?