Created
July 22, 2014 18:36
-
-
Save skehlet/4a10edc39482091569e3 to your computer and use it in GitHub Desktop.
This file contains 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.util.*; | |
import java.net.*; | |
public class ShowEth0PrimaryIp { | |
public static final String ETH0 = "eth0"; | |
public static void main(String[] args) throws Exception { | |
System.out.println(new ShowEth0PrimaryIp().getEth0PrimaryIp()); | |
} | |
public InetAddress getEth0PrimaryIp() throws SocketException { | |
List<InetAddress> tracker = new ArrayList<InetAddress>(); | |
NetworkInterface itf = NetworkInterface.getByName(ETH0); | |
List<InetAddress> allAddrs = getInetAddresses(itf); | |
for (InetAddress addr: allAddrs) { | |
tracker.add(addr); | |
} | |
Enumeration<NetworkInterface> subItfs = itf.getSubInterfaces(); | |
while (subItfs.hasMoreElements()) { | |
NetworkInterface subItf = subItfs.nextElement(); | |
List<InetAddress> subItfAddrs = getInetAddresses(subItf); | |
for (InetAddress subItfAddr: subItfAddrs) { | |
if (tracker.contains(subItfAddr)) { | |
System.out.println("Removing " + subItfAddr + " from all addrs"); | |
tracker.remove(subItfAddr); | |
} | |
} | |
} | |
if (tracker.size() != 1) { | |
System.out.println("Was hoping to whittle list down to 1, but didn't"); | |
} | |
return tracker.get(0); | |
} | |
private List<InetAddress> getInetAddresses(NetworkInterface itf) throws SocketException { | |
System.out.println("=== " + itf.getName() + " ==="); | |
List<InetAddress> myAddrs = new ArrayList<InetAddress>(); | |
Enumeration<InetAddress> addrs = itf.getInetAddresses(); | |
while (addrs.hasMoreElements()) { | |
InetAddress addr = addrs.nextElement(); | |
if ( | |
addr != null | |
&& !addr.isLoopbackAddress() | |
&& ( | |
itf.isPointToPoint() || !addr.isLinkLocalAddress() | |
) | |
) { | |
myAddrs.add(addr); | |
System.out.println("found: " + addr); | |
} | |
} | |
return myAddrs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment