下面列出了java.net.NetworkInterface#getInterfaceAddresses ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testInterfaceProperties() throws Exception {
for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
assertEquals(nif, NetworkInterface.getByName(nif.getName()));
// Skip interfaces that are inactive
if (nif.isUp() == false) {
continue;
}
// Ethernet
if (isEthernet(nif.getName())) {
assertEquals(6, nif.getHardwareAddress().length);
for (InterfaceAddress ia : nif.getInterfaceAddresses()) {
if (ia.getAddress() instanceof Inet4Address) {
assertNotNull(ia.getBroadcast());
}
}
}
}
}
public String[] getBroadcastAddresses() {
ArrayList<String> list = new ArrayList<>();
try {
System.setProperty("java.net.preferIPv4Stack", "true");
Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
while (niEnum.hasMoreElements()) {
NetworkInterface ni = niEnum.nextElement();
if (!ni.isLoopback()) {
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
if (interfaceAddress.getBroadcast() != null)
list.add(interfaceAddress.getBroadcast().toString().substring(1));
}
}
}
} catch (Exception ignored) {
}
return list.toArray(new String[list.size()]);
}
public static String getBroadcastAddress() {
System.setProperty("java.net.preferIPv4Stack", "true");
try {
for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum
.hasMoreElements();) {
NetworkInterface ni = niEnum.nextElement();
if (!ni.isLoopback()) {
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
if (interfaceAddress.getBroadcast() != null) {
logger.d(interfaceAddress.getBroadcast().toString().substring(1));
return interfaceAddress.getBroadcast().toString().substring(1);
}
}
}
}
}
catch (SocketException e) {
e.printStackTrace();
}
return null;
}
SpoofAddrFactory() throws Exception {
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
for (InterfaceAddress intAddress : netint.getInterfaceAddresses()) {
InetAddress addr = intAddress.getAddress();
if (addr instanceof Inet4Address) {
String cidr = String.format("%s/%d", addr.getHostAddress(), intAddress.getNetworkPrefixLength());
SubnetUtils subnet = new SubnetUtils(cidr);
subnets.add(subnet.getInfo());
if (defaultAddr == null) {
defaultAddr = addr.getHostAddress();
} else if (defaultAddr.equals("127.0.0.1")) {
defaultAddr = addr.getHostAddress();
}
}
}
}
}
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");
}
@Nullable
private final InterfaceAddress getNetworkInterfaceAddress(@Nullable NetworkInterface ni) {
if (ni == null) {
return null;
}
List<InterfaceAddress> addrs = ni.getInterfaceAddresses();
if (addrs == null || addrs.isEmpty()) {
return null;
}
// Prefer IPv4 addresses
for (InterfaceAddress address : addrs) {
if (address.getAddress() instanceof Inet4Address) {
return address;
}
}
// Use first IPv6 address if no others are present
return addrs.get(0);
}
/**
* @deprecated This method is no longer used by LittleProxy and may be removed in a future release.
*/
@Deprecated
public static InetAddress firstLocalNonLoopbackIpv4Address() {
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces
.nextElement();
if (networkInterface.isUp()) {
for (InterfaceAddress ifAddress : networkInterface
.getInterfaceAddresses()) {
if (ifAddress.getNetworkPrefixLength() > 0
&& ifAddress.getNetworkPrefixLength() <= 32
&& !ifAddress.getAddress().isLoopbackAddress()) {
return ifAddress.getAddress();
}
}
}
}
return null;
} catch (SocketException se) {
return null;
}
}
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");
}
public static String[] getLocalCidrs() {
final String defaultHostIp = getDefaultHostIp();
final List<String> cidrList = new ArrayList<String>();
try {
for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
final InetAddress addr = address.getAddress();
final int prefixLength = address.getNetworkPrefixLength();
if (prefixLength < MAX_CIDR && prefixLength > 0) {
final String ip = addr.getHostAddress();
if (ip.equalsIgnoreCase(defaultHostIp)) {
cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
}
}
}
}
}
} catch (final SocketException e) {
s_logger.warn("UnknownHostException in getLocalCidrs().", e);
}
return cidrList.toArray(new String[0]);
}
private static List<InetAddress> getBroadCastAddress() throws Exception {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
List<InetAddress> addresses = new ArrayList<InetAddress>();
addresses.add(InetAddress.getByName("255.255.255.255"));
while (interfaces.hasMoreElements()) {
NetworkInterface networkInterface = interfaces.nextElement();
if (networkInterface.isLoopback() || !networkInterface.supportsMulticast()) {
continue; // Don't want to broadcast to the loopback interface
}
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress broadcast = interfaceAddress.getBroadcast();
if (broadcast != null) {
addresses.add(broadcast);
}
}
}
return addresses;
}
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");
}
public static String[] getNetworkParams(final NetworkInterface nic) {
final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
if (addrs == null || addrs.size() == 0) {
return null;
}
InterfaceAddress addr = null;
for (final InterfaceAddress iaddr : addrs) {
final InetAddress inet = iaddr.getAddress();
if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
addr = iaddr;
break;
}
}
if (addr == null) {
return null;
}
final String[] result = new String[3];
result[0] = addr.getAddress().getHostAddress();
try {
final byte[] mac = nic.getHardwareAddress();
result[1] = byte2Mac(mac);
} catch (final SocketException e) {
s_logger.debug("Caught exception when trying to get the mac address ", e);
}
result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
return result;
}
/**
* Get IPv4 Subnet
* @param inetAddress
* @return
*/
public static String getIPv4Subnet(InetAddress inetAddress) {
try {
NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress);
List<InterfaceAddress> intAddrs = ni.getInterfaceAddresses();
for (InterfaceAddress ia : intAddrs) {
if (!ia.getAddress().isLoopbackAddress() && ia.getAddress() instanceof Inet4Address) {
return getIPv4SubnetFromNetPrefixLength(ia.getNetworkPrefixLength()).getHostAddress()
.toString();
}
}
} catch (Exception e) {
}
return "";
}
private @Nullable String getIPv4inSubnet(String ipAddress, String subnetMask) {
try {
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
final NetworkInterface current = interfaces.nextElement();
if (!current.isUp() || current.isLoopback() || current.isVirtual() || current.isPointToPoint()) {
continue;
}
for (InterfaceAddress ifAddr : current.getInterfaceAddresses()) {
InetAddress addr = ifAddr.getAddress();
if (addr.isLoopbackAddress() || (addr instanceof Inet6Address)) {
continue;
}
String ipv4AddressOnInterface = addr.getHostAddress();
String subnetStringOnInterface = getIpv4NetAddress(ipv4AddressOnInterface,
ifAddr.getNetworkPrefixLength()) + "/" + String.valueOf(ifAddr.getNetworkPrefixLength());
String configuredSubnetString = getIpv4NetAddress(ipAddress, Short.parseShort(subnetMask)) + "/"
+ subnetMask;
// use first IP within this subnet
if (subnetStringOnInterface.equals(configuredSubnetString)) {
return ipv4AddressOnInterface;
}
}
}
} catch (SocketException ex) {
LOGGER.error("Could not retrieve network interface: {}", ex.getMessage(), ex);
}
return null;
}
public void testLoopback() throws Exception {
NetworkInterface lo = NetworkInterface.getByName("lo0");
assertNull(lo.getHardwareAddress());
for (InterfaceAddress ia : lo.getInterfaceAddresses()) {
assertNull(ia.getBroadcast());
}
}
private NetworkInterface findNetworkInterface() throws SocketException {
String name = (String)this.getEndpointInfo().getProperty(UDPDestination.NETWORK_INTERFACE);
NetworkInterface ret = null;
if (!StringUtils.isEmpty(name)) {
ret = NetworkInterface.getByName(name);
}
if (ret == null) {
Enumeration<NetworkInterface> ifcs = NetworkInterface.getNetworkInterfaces();
List<NetworkInterface> possibles = new ArrayList<>();
while (ifcs.hasMoreElements()) {
NetworkInterface ni = ifcs.nextElement();
if (ni.supportsMulticast()
&& ni.isUp()) {
for (InterfaceAddress ia : ni.getInterfaceAddresses()) {
if (ia.getAddress() instanceof java.net.Inet4Address
&& !ia.getAddress().isLoopbackAddress()
&& !ni.getDisplayName().startsWith("vnic")) {
possibles.add(ni);
}
}
}
}
ret = possibles.isEmpty() ? null : possibles.get(possibles.size() - 1);
}
return ret;
}
public void buildNetworkSnapshot() {
try {
NetworkInformation netInfo = new NetworkInformation();
netInfo.setTotalMemory(Runtime.getRuntime().maxMemory());
netInfo.setAvailableMemory(Runtime.getRuntime().freeMemory());
String sparkIp = System.getenv("SPARK_PUBLIC_DNS");
if (sparkIp != null) {
// if spark ip is defined, we just use it, and don't bother with other interfaces
netInfo.addIpAddress(sparkIp);
} else {
// sparkIp wasn't defined, so we'll go for heuristics here
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface networkInterface : interfaces) {
if (networkInterface.isLoopback() || !networkInterface.isUp())
continue;
for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
String addr = address.getAddress().getHostAddress();
if (addr == null || addr.isEmpty() || addr.contains(":"))
continue;
netInfo.getIpAddresses().add(addr);
}
}
}
networkInformation.add(netInfo);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void startReceivers(NetworkInterface ni, String udpMulticast, boolean udpBroadcast) throws Exception {
if (ni == null || ni.isLoopback()) {
return;
}
List<InterfaceAddress> list = ni.getInterfaceAddresses();
if (list == null || list.isEmpty()) {
return;
}
if (udpMulticast != null && ni.supportsMulticast()) {
// Create multicast receiver
receivers.add(new UDPMulticastReceiver(nodeID, udpMulticast, transporter, ni));
}
if (udpBroadcast) {
for (InterfaceAddress ia : list) {
if (ia == null) {
continue;
}
InetAddress address = ia.getBroadcast();
if (address == null || address.isLoopbackAddress()) {
continue;
}
String udpAddress = address.getHostAddress();
if (udpAddress == null || udpAddress.isEmpty() || udpAddress.startsWith("127.")) {
continue;
}
// Create broadcast receiver
receivers.add(new UDPBroadcastReceiver(nodeID, udpAddress, transporter));
}
}
}
public static Set<InetSocketAddress> getLocalAddresses ( final IoAcceptor acceptor ) throws SocketException
{
final Set<InetSocketAddress> result = new HashSet<InetSocketAddress> ();
for ( final SocketAddress address : acceptor.getLocalAddresses () )
{
logger.info ( "Bound to: {}", address );
if ( ! ( address instanceof InetSocketAddress ) )
{
continue;
}
final InetSocketAddress socketAddress = (InetSocketAddress)address;
if ( socketAddress.getAddress ().isAnyLocalAddress () )
{
final int port = socketAddress.getPort ();
final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces ();
while ( interfaces.hasMoreElements () )
{
final NetworkInterface networkInterface = interfaces.nextElement ();
for ( final InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses () )
{
result.add ( new InetSocketAddress ( interfaceAddress.getAddress (), port ) );
}
}
}
else
{
result.add ( socketAddress );
}
}
return result;
}
private void generatePrivateKeyAndCertificate()
{
try
{
Set<InetAddress> addresses = new HashSet<>();
for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces()))
{
for (InterfaceAddress inetAddress : networkInterface.getInterfaceAddresses())
{
addresses.add(inetAddress.getAddress());
}
}
Set<String> dnsNames = new HashSet<>();
for(InetAddress address : addresses)
{
String hostName = address.getHostName();
if (hostName != null)
{
dnsNames.add(hostName);
}
String canonicalHostName = address.getCanonicalHostName();
if (canonicalHostName != null)
{
dnsNames.add(canonicalHostName);
}
}
long startTime = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(startTime);
calendar.add(Calendar.MONTH, _durationInMonths);
long duration = (calendar.getTimeInMillis() - startTime)/1000;
final SSLUtil.KeyCertPair keyCertPair = SSLUtil.generateSelfSignedCertificate(_keyAlgorithm,
_signatureAlgorithm,
_keyLength,
startTime,
duration,
"CN=Qpid",
dnsNames,
addresses);
_privateKey = keyCertPair.getPrivateKey();
_certificate = keyCertPair.getCertificate();
_generated = true;
}
catch (InstantiationException | IllegalAccessException | InvocationTargetException | IOException e)
{
throw new IllegalConfigurationException("Unable to construct keystore", e);
}
}