下面列出了怎么用java.net.NetworkInterface的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws Exception {
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
NetworkInterface nic = nics.nextElement();
for (InterfaceAddress iaddr : nic.getInterfaceAddresses()) {
boolean valid = checkPrefix(iaddr);
if (!valid) {
passed = false;
debug(nic.getName(), iaddr);
}
InetAddress ia = iaddr.getAddress();
if (ia.isLoopbackAddress() && ia instanceof Inet4Address) {
// assumption: prefix length will always be 8
if (iaddr.getNetworkPrefixLength() != 8) {
out.println("Expected prefix of 8, got " + iaddr);
passed = false;
}
}
}
}
if (!passed)
throw new RuntimeException("Failed: some interfaces have invalid prefix lengths");
}
/**
* Create a new broadcaster
*
* @param address - multicast group address
* @param srcAddress - address of interface we should use to broadcast.
* @param port - udp port to use
* @param ttl - packet ttl
* @throws IOException
*/
public JdpBroadcaster(InetAddress address, InetAddress srcAddress, int port, int ttl)
throws IOException, JdpException {
this.addr = address;
this.port = port;
ProtocolFamily family = (address instanceof Inet6Address)
? StandardProtocolFamily.INET6 : StandardProtocolFamily.INET;
channel = DatagramChannel.open(family);
channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
channel.setOption(StandardSocketOptions.IP_MULTICAST_TTL, ttl);
// with srcAddress equal to null, this constructor do exactly the same as
// if srcAddress is not passed
if (srcAddress != null) {
// User requests particular interface to bind to
NetworkInterface interf = NetworkInterface.getByInetAddress(srcAddress);
try {
channel.bind(new InetSocketAddress(srcAddress, 0));
} catch (UnsupportedAddressTypeException ex) {
throw new JdpException("Unable to bind to source address");
}
channel.setOption(StandardSocketOptions.IP_MULTICAST_IF, interf);
}
}
private boolean ensureIPv6OnLoopback() throws Exception {
boolean ipv6 = false;
List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nic : nics) {
if (!nic.isLoopback()) {
continue;
}
List<InetAddress> addrs = Collections.list(nic.getInetAddresses());
for (InetAddress addr : addrs) {
if (addr instanceof Inet6Address) {
ipv6 = true;
break;
}
}
}
if (!ipv6)
System.out.println("IPv6 is not enabled on loopback. Skipping test suite.");
return ipv6;
}
public static String getHostName() throws SocketException {
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration<InetAddress> ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
if (!i.isSiteLocalAddress() && !i.isLinkLocalAddress() && !i.isLoopbackAddress() && !i.isAnyLocalAddress() && !i.isMulticastAddress()) {
return i.getHostName();
}
}
}
throw new SocketException("Failed to get the IP address for the local host");
}
public static List<String> getLocalInetAddress() {
List<String> inetAddressList = new ArrayList<String>();
try {
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface networkInterface = enumeration.nextElement();
Enumeration<InetAddress> addrs = networkInterface.getInetAddresses();
while (addrs.hasMoreElements()) {
inetAddressList.add(addrs.nextElement().getHostAddress());
}
}
} catch (SocketException e) {
throw new RuntimeException("get local inet address fail", e);
}
return inetAddressList;
}
public static boolean isConnectedToLocalNetwork(Context context) {
boolean connected = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
connected = ni != null
&& ni.isConnected()
&& (ni.getType() & (ConnectivityManager.TYPE_WIFI | ConnectivityManager.TYPE_ETHERNET)) != 0;
if (!connected) {
Log.d(TAG, "isConnectedToLocalNetwork: see if it is an USB AP");
try {
for (NetworkInterface netInterface : Collections.list(NetworkInterface
.getNetworkInterfaces())) {
if (netInterface.getDisplayName().startsWith("rndis")) {
connected = true;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
}
return connected;
}
private static boolean isIpAddrAvailable (NetworkInterface netIf) {
boolean ipAddrAvailable = false;
byte[] nullIpAddr = {'0', '0', '0', '0'};
byte[] testIpAddr = null;
Enumeration<InetAddress> ipAddresses = netIf.getInetAddresses();
while (ipAddresses.hasMoreElements()) {
InetAddress testAddr = ipAddresses.nextElement();
testIpAddr = testAddr.getAddress();
if ((testIpAddr != null) && (!Arrays.equals(testIpAddr, nullIpAddr))) {
ipAddrAvailable = true;
break;
} else {
System.out.println("ignore netif " + netIf.getName());
}
}
return ipAddrAvailable;
}
/**
* 获取所有ipv6地址
*
* @return hash map
*/
public static Map<String, String> getLocalIPV6() {
Map<String, String> map = new HashMap<>();
InetAddress ip = null;
try {
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = ips.nextElement();
if (ip instanceof Inet6Address) {
map.put(ni.getName(), ip.getHostAddress());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 得到ip地址
*
* @return
*/
public static String getLocalIpAddress() {
String ret = "";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
ret = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return ret;
}
@Description("Returns the IPv4 for the specified network interface name.<br>" +
"<b>interfaceName</b> - the network interface name, the IP of which will be returned<br>" +
"Example:<br/>" +
"#{currentIpAddress(interfaceName)}")
@UtilityMethod
public String currentIpAddress(String interfaceName) {
try {
NetworkInterface networkInterface = NetworkInterface.getByName(interfaceName);
if (networkInterface == null) {
throw new EPSCommonException("Unknown interface name: " + interfaceName);
}
Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
InetAddress address;
while (addresses.hasMoreElements()) {
address = addresses.nextElement();
if (address instanceof Inet4Address) {
return address.getHostAddress();
}
}
throw new EPSCommonException(String.format("Network interface %s has not IPv4", interfaceName));
} catch (Exception e) {
throw new EPSCommonException(String.format("Can't get interface [%s]", interfaceName), e);
}
}
/**
* 获取本地ip地址,有可能会有多个地址, 若有多个网卡则会搜集多个网卡的ip地址
*/
public static Set<InetAddress> resolveLocalAddresses() {
Set<InetAddress> addrs = new HashSet<InetAddress>();
Enumeration<NetworkInterface> ns = null;
try {
ns = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
// ignored...
}
while (ns != null && ns.hasMoreElements()) {
NetworkInterface n = ns.nextElement();
Enumeration<InetAddress> is = n.getInetAddresses();
while (is.hasMoreElements()) {
InetAddress i = is.nextElement();
if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
&& !isSpecialIp(i.getHostAddress())) addrs.add(i);
}
}
return addrs;
}
private boolean isCurrentHostMaster() throws SocketException {
logger.debug("[Rainfall master] Check if the current host should start the master.");
InetAddress masterAddress = distributedConfig.getMasterAddress().getAddress();
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
logger.debug("[Rainfall naster] Check NIC list.");
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
logger.debug("[Rainfall master] Check if current NIC ({}) has the IP from rainfall master host ({}).",
inetAddress, masterAddress);
if (inetAddress.equals(masterAddress)) {
logger.debug("[Rainfall master] Current NIC IP is the one from the DistributedConfiguration, attempt to start the master process.");
return true;
}
}
}
return false;
}
static void testAllNetworkInterfaces() throws Exception {
System.err.println("\n testAllNetworkInterfaces: \n ");
for (Enumeration<NetworkInterface> e = NetworkInterface
.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface netIF = e.nextElement();
for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
.hasMoreElements();) {
InetAddress iadr = iadrs.nextElement();
if (iadr instanceof Inet6Address) {
System.err.println("Test NetworkInterface: " + netIF);
Inet6Address i6adr = (Inet6Address) iadr;
System.err.println("Testing with " + iadr);
System.err.println(" scoped iface: "
+ i6adr.getScopedInterface());
testInet6AddressSerialization(i6adr, null);
}
}
}
}
public static InetAddress getBroadcast(){
InetAddress found_bcast_address=null;
System.setProperty("java.net.preferIPv4Stack", "true");
try
{
Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
while (niEnum.hasMoreElements())
{
NetworkInterface ni = niEnum.nextElement();
if(!ni.isLoopback()){
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
{
found_bcast_address = interfaceAddress.getBroadcast();
}
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
return found_bcast_address;
}
private boolean testMacAddressesEqual(NetworkInterface netIf1,
NetworkInterface netIf2) throws Exception {
byte[] rawMacAddress1 = null;
byte[] rawMacAddress2 = null;
boolean macAddressesEqual = false;
if (!netIf1.getName().equals(netIf2.getName())) {
System.out.println("compare hardware addresses "
+ createMacAddressString(netIf1) + " and " + createMacAddressString(netIf2));
rawMacAddress1 = netIf1.getHardwareAddress();
rawMacAddress2 = netIf2.getHardwareAddress();
macAddressesEqual = Arrays.equals(rawMacAddress1, rawMacAddress2);
} else {
// same interface
macAddressesEqual = false;
}
return macAddressesEqual;
}
private static void configureSuperUserIPAddresses(Configuration conf,
String superUserShortName) throws IOException {
ArrayList<String> ipList = new ArrayList<String>();
Enumeration<NetworkInterface> netInterfaceList = NetworkInterface
.getNetworkInterfaces();
while (netInterfaceList.hasMoreElements()) {
NetworkInterface inf = netInterfaceList.nextElement();
Enumeration<InetAddress> addrList = inf.getInetAddresses();
while (addrList.hasMoreElements()) {
InetAddress addr = addrList.nextElement();
ipList.add(addr.getHostAddress());
}
}
StringBuilder builder = new StringBuilder();
for (String ip : ipList) {
builder.append(ip);
builder.append(',');
}
builder.append("127.0.1.1,");
builder.append(InetAddress.getLocalHost().getCanonicalHostName());
LOG.info("Local Ip addresses: " + builder.toString());
conf.setStrings(DefaultImpersonationProvider.getTestProvider().
getProxySuperuserIpConfKey(superUserShortName),
builder.toString());
}
/**
* Returns a list of all the addresses on the system.
* @param inclLoopback
* if {@code true}, include the loopback addresses
* @param ipv4Only
* it {@code true}, only IPv4 addresses will be included
*/
static List<InetAddress> getAddresses(boolean inclLoopback,
boolean ipv4Only)
throws SocketException {
ArrayList<InetAddress> list = new ArrayList<InetAddress>();
Enumeration<NetworkInterface> nets =
NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netInf : Collections.list(nets)) {
Enumeration<InetAddress> addrs = netInf.getInetAddresses();
for (InetAddress addr : Collections.list(addrs)) {
if (!list.contains(addr) &&
(inclLoopback ? true : !addr.isLoopbackAddress()) &&
(ipv4Only ? (addr instanceof Inet4Address) : true)) {
list.add(addr);
}
}
}
return list;
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
if (null != mac) {
id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
}
} catch (Exception e) {
logger.warn(" getDatacenterId: " + e.getMessage());
}
return id;
}
@Test
public void testConnectorToServerAcceptingAListOfHosts_2() throws Exception {
Map<NetworkInterface, InetAddress> map = NetworkAddressTestBase.getAddressForEachNetworkInterface();
if (map.size() <= 2) {
System.err.println("There must be at least 3 network interfaces: test will not be executed");
return;
}
Set<Entry<NetworkInterface, InetAddress>> set = map.entrySet();
Iterator<Entry<NetworkInterface, InetAddress>> iterator = set.iterator();
Entry<NetworkInterface, InetAddress> entry1 = iterator.next();
Entry<NetworkInterface, InetAddress> entry2 = iterator.next();
Entry<NetworkInterface, InetAddress> entry3 = iterator.next();
String listOfHosts = entry1.getValue().getHostAddress() + ", " + entry2.getValue().getHostAddress();
testConnection(listOfHosts, entry1.getValue().getHostAddress(), true, 0);
testConnection(listOfHosts, entry2.getValue().getHostAddress(), true, 0);
testConnection(listOfHosts, entry3.getValue().getHostAddress(), false, 0);
}
static void displayExpectedInet6Address(Inet6Address expectedInet6Address) {
String expectedHostName = expectedInet6Address.getHostName();
byte[] expectedAddress = expectedInet6Address.getAddress();
String expectedHostAddress = expectedInet6Address.getHostAddress();
int expectedScopeId = expectedInet6Address.getScopeId();
NetworkInterface expectedNetIf = expectedInet6Address
.getScopedInterface();
System.err.println("Excpected HostName: " + expectedHostName);
System.err.println("Expected Address: "
+ Arrays.toString(expectedAddress));
System.err.println("Expected HostAddress: " + expectedHostAddress);
System.err.println("Expected Scope Id " + expectedScopeId);
System.err.println("Expected NetworkInterface " + expectedNetIf);
System.err.println("Expected Inet6Address " + expectedInet6Address);
}
public static String[] getLocalIpAddresses(){
try {
ArrayList<String> alAddresses = new ArrayList<String>();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()&& InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
alAddresses.add(inetAddress.getHostAddress());
}
}
}
return alAddresses.toArray(new String[alAddresses.size()]);
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
protected InetAddress getBindAddressInSubnetOf(InetAddress inetAddress) {
synchronized (networkInterfaces) {
for (NetworkInterface iface : networkInterfaces) {
for (InterfaceAddress ifaceAddress : getInterfaceAddresses(iface)) {
synchronized (bindAddresses) {
if (ifaceAddress == null || !bindAddresses.contains(ifaceAddress.getAddress())) {
continue;
}
}
if (isInSubnet(
inetAddress.getAddress(),
ifaceAddress.getAddress().getAddress(),
ifaceAddress.getNetworkPrefixLength())
) {
return ifaceAddress.getAddress();
}
}
}
}
return null;
}
protected ArrayList<NetworkInterfaceBase> getNetworkInterfaces()
{
ArrayList<NetworkInterfaceBase> interfaceList = new ArrayList<>();
try {
Enumeration<NetworkInterface> ifaceEnum
= NetworkInterface.getNetworkInterfaces();
while (ifaceEnum.hasMoreElements()) {
NetworkInterface iface = ifaceEnum.nextElement();
interfaceList.add(new NetworkInterfaceTcp(iface));
}
} catch (Exception e) {
log.log(Level.WARNING, e.toString(), e);
}
return interfaceList;
}
public final InetAddress getLocalAddress() throws SocketException {
for (final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces
.hasMoreElements();) {
final NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback()) {
continue;
}
for (final InterfaceAddress interfaceAddr : networkInterface.getInterfaceAddresses()) {
final InetAddress inetAddr = interfaceAddr.getAddress();
if (!(inetAddr instanceof Inet4Address)) {
continue;
}
return inetAddr;
}
}
return null;
}
public static void main(String... args) throws Exception {
NetworkConfiguration.printSystemConfiguration(out);
NetworkConfiguration nc = NetworkConfiguration.probe();
String list;
list = nc.ip4MulticastInterfaces()
.map(NetworkInterface::getName)
.collect(joining(" "));
out.println("ip4MulticastInterfaces: " + list);
list = nc.ip4Addresses()
.map(Inet4Address::toString)
.collect(joining(" "));
out.println("ip4Addresses: " + list);
list = nc.ip6MulticastInterfaces()
.map(NetworkInterface::getName)
.collect(joining(" "));
out.println("ip6MulticastInterfaces: " + list);
list = nc.ip6Addresses()
.map(Inet6Address::toString)
.collect(joining(" "));
out.println("ip6Addresses: " + list);
}
public static List<String> getEnvironment() {
List<String> environment = new ArrayList<String>();
environment.add("OS: " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch", ""));
environment.add("CPU: " + Runtime.getRuntime().availableProcessors() + " cores");
environment.add("JVM: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version"));
environment.add("Memory: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().totalMemory())
+ " bytes (Max: " + DecimalFormat.getIntegerInstance().format(Runtime.getRuntime().maxMemory()) + " bytes)");
NetworkInterface ni = PerformanceUtils.getNetworkInterface();
if (ni != null) {
environment.add("Network: " + ni.getDisplayName());
}
return environment;
}
static List<Inet6Address> getAllInet6Addresses() throws Exception {
// System.err.println("\n getAllInet6Addresses: \n ");
ArrayList<Inet6Address> inet6Addresses = new ArrayList<Inet6Address>();
for (Enumeration<NetworkInterface> e = NetworkInterface
.getNetworkInterfaces(); e.hasMoreElements();) {
NetworkInterface netIF = e.nextElement();
for (Enumeration<InetAddress> iadrs = netIF.getInetAddresses(); iadrs
.hasMoreElements();) {
InetAddress iadr = iadrs.nextElement();
if (iadr instanceof Inet6Address) {
System.err.println("Test NetworkInterface: " + netIF);
Inet6Address i6adr = (Inet6Address) iadr;
System.err.println(" address " + iadr);
System.err.println(" scoped iface: "
+ i6adr.getScopedInterface());
// using this to actually set the hostName for an
// InetAddress
// created through the NetworkInterface
// have found that the fabricated instances has a null
// hostName
System.err.println(" hostName: " + i6adr.getHostName());
inet6Addresses.add(i6adr);
}
}
}
return inet6Addresses;
}
/**
* Get non-loopback address. InetAddress.getLocalHost() does not work on machines without static ip address.
*
* @param ni target network interface
* @param preferIPv4 true iff require IPv4 addresses only
* @param preferIPv6 true iff prefer IPv6 addresses
* @return nonLoopback {@link InetAddress}
* @throws SocketException
*/
private static InetAddress getFirstNonLoopbackAddress(NetworkInterface ni,
boolean preferIPv4,
boolean preferIPv6) throws SocketException {
InetAddress result = null;
// skip virtual interface name, PTP and non-running interface.
if (ni.isVirtual() || ni.isPointToPoint() || ! ni.isUp()) {
return result;
}
LOG.info("Interface name is: " + ni.getDisplayName());
for (Enumeration en2 = ni.getInetAddresses(); en2.hasMoreElements(); ) {
InetAddress addr = (InetAddress) en2.nextElement();
if (!addr.isLoopbackAddress()) {
if (addr instanceof Inet4Address) {
if (preferIPv6) {
continue;
}
result = addr;
break;
}
if (addr instanceof Inet6Address) {
if (preferIPv4) {
continue;
}
result = addr;
break;
}
}
}
return result;
}
public String getSeries() {
// try {
//// NativeInterfaces.setLibDir(new File("lib"));
// NativeInterfaces.setLibDir(new File(FileLocator.toFileURL(Platform.getBundle("net.heartsome.cat.ts.help").getEntry("")).getPath()
// + File.separator + System.getProperty("sun.arch.data.model")));
// EthernetAddress[] macs = NativeInterfaces.getAllInterfaces();
// String series = "";
// for (EthernetAddress a : macs) {
// series += a.toString() + "+";
// }
// return "".equals(series) ? null : StringUtils.removeColon(series.substring(0, series.length() - 1));
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// }
try {
String series = "";
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface network = networkInterfaces.nextElement();
if (!network.getName().startsWith("vmnet") && !network.getName().startsWith("vboxnet")) {
byte[] mac = network.getHardwareAddress();
if (mac != null && mac.length == 6 && !network.isLoopback() && !network.isVirtual()) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02x", mac[i]));
}
sb.append("+");
series += sb.toString();
}
}
}
return "".equals(series) ? null : series.substring(0, series.length() - 1);
} catch (SocketException e) {
e.printStackTrace();
return null;
}
}
public String getMacAddressAsString(NetworkInterface ni) {
byte[] mac = null;
try {
mac = ni.getHardwareAddress();
}
catch (SocketException e) {
return null;
}
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append(":");
}
// 字节转换为整数
int temp = mac[i] & 0xff;
String str = Integer.toHexString(temp);
if (str.length() == 1) {
sb.append("0" + str);
}
else {
sb.append(str);
}
}
return sb.toString().toUpperCase();
}