Skip to content

Instantly share code, notes, and snippets.

@ywindish
Last active August 29, 2015 14:07
Show Gist options
  • Save ywindish/4eae6401721b0faff338 to your computer and use it in GitHub Desktop.
Save ywindish/4eae6401721b0faff338 to your computer and use it in GitHub Desktop.
ブロードキャストアドレスを得る
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class BroadcastAddressTest {
public static void main(String[] args) throws SocketException {
BroadcastAddressTest client = new BroadcastAddressTest();
System.out.println(client.getBroadcastAddress().toString());
}
public InetAddress getBroadcastAddress() throws SocketException {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface nif = networkInterfaces.nextElement();
if (nif.isLoopback() || !nif.isUp()) {
// ループバックまたは起動してないインタフェースは無視する
continue;
}
List<InterfaceAddress> addresses = nif.getInterfaceAddresses();
for (InterfaceAddress address : addresses) {
InetAddress broadcast = address.getBroadcast();
if (broadcast != null) {
// 最初に見つかったブロードキャストアドレスを返す
return broadcast;
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment