Skip to content

Instantly share code, notes, and snippets.

@md-5
Created August 19, 2012 01:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save md-5/3390780 to your computer and use it in GitHub Desktop.
Save md-5/3390780 to your computer and use it in GitHub Desktop.
Shows your Bukkit server to the LAN
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);
}
}
}
@md-5
Copy link
Author

md-5 commented Oct 27, 2012

Try: byte[] broadcast = ("[MOTD]" + getServer().getMotd() + "[/MOTD][AD]" + InetAddress.getLocalHost() + ":" + getServer().getPort() + "[/AD]").getBytes();

@zhuowei
Copy link

zhuowei commented Oct 27, 2012

That's what Minecraft itself uses pretty much and what I use in my slightly modified version, but thanks again.

@Tsaukpaetra
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment