Last active
December 18, 2015 02:19
-
-
Save bbeaudreault/5710269 to your computer and use it in GitHub Desktop.
Alternate implementation of Bookie#getBookieAddress(ServerConfiguration conf) which is configurable to look at a specific interface.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetAddress; | |
import java.net.InetSocketAddress; | |
import java.net.InterfaceAddress; | |
import java.net.NetworkInterface; | |
import java.net.SocketException; | |
import java.net.UnknownHostException; | |
import org.apache.bookkeeper.conf.ServerConfiguration; | |
public class Bookie { | |
public static InetSocketAddress getBookieAddress(ServerConfiguration conf) throws UnknownHostException, SocketException { | |
String hostInterface = conf.getString("bookie.host.interface", "default"); | |
boolean useIpv6 = conf.getBoolean("bookie.host.useIpv6", false); | |
InetAddress addr = getLocalInetAddrForInterface(hostInterface, useIpv6); | |
return new InetSocketAddress(addr, conf.getBookiePort()); | |
} | |
private static InetAddress getLocalInetAddrForInterface(String hostInterface, boolean useIpv6) throws UnknownHostException, SocketException { | |
if (hostInterface.equals("default")) { | |
return InetAddress.getLocalHost(); | |
} | |
NetworkInterface netInt = NetworkInterface.getByName(hostInterface); | |
for (InterfaceAddress addr : netInt.getInterfaceAddresses()) { | |
// The List<InterfaceAddresses> includes the ipv4 and ipv6 (if available) addresses associated with the interface | |
// ipv6 does not have a broadcast, so getBroadcast returns null. Use this to return the right InetAddress based on the value of useIpv6 | |
if ((addr.getBroadcast() == null && useIpv6) || (addr.getBroadcast() != null && !useIpv6)) { | |
return addr.getAddress(); | |
} | |
} | |
throw new UnknownHostException("Did not find a reasonable InetAddress for hostInterface=" + hostInterface + ", useIpv6=" + useIpv6); | |
} | |
public static void main(String[] args) throws UnknownHostException, SocketException { | |
ServerConfiguration conf = new ServerConfiguration(); | |
System.out.println(Bookie.getBookieAddress(conf)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment