下面列出了java.net.NetworkInterface#getByInetAddress ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static final long getHostId(){
long macAddressAsLong = 0;
try {
Random random = new Random();
InetAddress address = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni != null) {
byte[] mac = ni.getHardwareAddress();
random.nextBytes(mac); // we don't really want to reveal the actual MAC address
//Converts array of unsigned bytes to an long
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
macAddressAsLong <<= 8;
macAddressAsLong ^= (long)mac[i] & 0xFF;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return macAddressAsLong;
}
/**
* Initialize remote address info.
*
* @param remoteAddressInfos the remote address infos
* @param inetAddress the inet address
*/
@SuppressWarnings("static-access")
private static void initializeRemoteAddressInfo(final List<String> remoteAddressInfos, final InetAddress inetAddress) {
if (inetAddress == null) {
return;
}
try {
final NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
final Enumeration<NetworkInterface> networkInterfaceEnum = networkInterface.getNetworkInterfaces();
while (networkInterfaceEnum.hasMoreElements()) {
final NetworkInterface nextNetworkInterfaceElement = networkInterfaceEnum.nextElement();
final Enumeration<InetAddress> inetAddressEnum = nextNetworkInterfaceElement.getInetAddresses();
while (inetAddressEnum.hasMoreElements()) {
final InetAddress nextInetAddressElement = inetAddressEnum.nextElement();
remoteAddressInfos.add(nextInetAddressElement.getHostAddress());
}
}
} catch (final Exception exception) {
LOGGER.error("An error occurred while searching for a network interface that has specified address bound to it - {}" + inetAddress, exception);
}
}
/**
* 通过 InetAddress 获取 Mac 地址
* @return Mac 地址
*/
private static String getMacAddressByInetAddress() {
try {
InetAddress inetAddress = getInetAddress();
if (inetAddress != null) {
NetworkInterface ni = NetworkInterface.getByInetAddress(inetAddress);
if (ni != null) {
byte[] macBytes = ni.getHardwareAddress();
if (macBytes != null && macBytes.length > 0) {
StringBuilder builder = new StringBuilder();
for (byte b : macBytes) {
builder.append(String.format("%02x:", b));
}
return builder.substring(0, builder.length() - 1);
}
}
}
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getMacAddressByInetAddress");
}
return DEFAULT_MAC_ADDRESS;
}
/**
* 获取机器编码 用来做数据ID
* 数据标识id部分 通常不建议采用下面的MAC地址方式,
* 因为用户通过破解很容易拿到MAC进行破坏
*/
protected static long getDataCenterId(long tempMaxDataCenterId) {
if (tempMaxDataCenterId < 0L || tempMaxDataCenterId > MAX_DATA_CENTER_ID) {
tempMaxDataCenterId = MAX_DATA_CENTER_ID;
}
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (tempMaxDataCenterId + 1);
}
} catch (Exception e) {
LOGGER.error("getDatacenterId:{}", e.getMessage());
}
return id;
}
/**
* <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;
}
/**
* 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);
}
}
public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException {
if (address instanceof Inet6Address) {
Inet6Address inet6Address = (Inet6Address) address;
if (inet6Address.getScopeId() == 0 && inet6Address.isLinkLocalAddress()) {
// Linux won't let you bind a link-local address without a scope id.
// Find one.
NetworkInterface nif = NetworkInterface.getByInetAddress(address);
if (nif == null) {
throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
}
try {
address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
} catch (UnknownHostException ex) {
throw new AssertionError(ex); // Can't happen.
}
}
}
try {
NetworkOs.bind(fd, address, port);
} catch (ErrnoException errnoException) {
throw new BindException(errnoException.getMessage(), errnoException);
}
}
/**
* <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();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
public static String extractValidHostname(String hostNameList, boolean[] localFound) throws UnknownHostException {
boolean x = localFound != null && localFound.length > 0;
if(x) localFound[0] = false;
if(hostNameList != null) {
hostNameList = hostNameList.trim();
if(!"".equals(hostNameList)) {
String[] arr = hostNameList.split("[,;]");
for(int i = 0; i < arr.length; i++) {
try {
InetAddress a = InetAddress.getByName(arr[i]);
if(x) {
if(a.isLoopbackAddress()) {
localFound[0] = true;
} else {
try {
localFound[0] = NetworkInterface.getByInetAddress(a) != null;
} catch (SocketException e) {
}
}
}
return arr[i];
} catch (UnknownHostException ex) {
}
}
throw new UnknownHostException("No valid IP address could be found in the specification: \"" + hostNameList + "\".");
}
}
if(x) localFound[0] = true;
return "127.0.0.1";
}
/**
* Method that searches for and returns an array whose elements
* are all the network interface(s) that correspond to the specified
* <code>name</code>.
*
* @param name <code>String</code> referencing the name to which
* the desired network interface(s) correspond.
*
* @return an array whose elements are each instances of
* <code>NetworkInterface[]</code>, in which each such
* instance corresponds to the given <code>name</code>,
* or <code>null</code> if there is no network interface
* corresponding to that name value.
*
* Note that if the value given for the <code>name</code>
* parameter is the <code>String</code> "all", then this
* method will return an array containing all of the
* network interfaces installed on the current node,
* regardless of each interface's name.
*
* @throws SocketException if there is an error in the underlying
* I/O subsystem and/or protocol.
*
* @throws NullPointerException if <code>null</code> is input for
* <code>name</code>.
*/
public static NetworkInterface[] getNetworkInterfaceArray(String name)
throws SocketException
{
NetworkInterface [] nics = null;
if (name.equals("all")) {
Enumeration en = NetworkInterface.getNetworkInterfaces();
List nicList = (en != null) ?
Collections.list(en) : Collections.EMPTY_LIST;
nics = (NetworkInterface[])(nicList.toArray
(new NetworkInterface[nicList.size()]) );
} else {
nics = new NetworkInterface[1];
nics[0] = NetworkInterface.getByName(name);
if (nics[0] == null) {
// try to lookup by IP address
InetAddress targetIp = null;
try {
targetIp = InetAddress.getByName(name);
nics[0] = NetworkInterface.getByInetAddress(targetIp);
} catch (UnknownHostException uhe) {
// ignore, return null
}
}
}
return nics;
}
public static void main(String[] args) {
try {
InetAddress addr = InetAddress.getByName("localhost");
if (!addr.isReachable(10000))
throw new RuntimeException("Localhost should always be reachable");
NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
if (inf != null) {
if (!addr.isReachable(inf, 20, 10000))
throw new RuntimeException("Localhost should always be reachable");
}
} catch (IOException e) {
throw new RuntimeException("Unexpected exception:" + e);
}
}
/**
* Returns interface MAC by index.
*
* @param interfaceIndex interface index
* @return interface IP by index
*/
private String getInterfaceMask(int interfaceIndex) {
String subnetMask = null;
try {
Ip4Address ipAddress = getInterfaceIp(interfaceIndex);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(
InetAddress.getByName(ipAddress.toString()));
Enumeration ipAddresses = networkInterface.getInetAddresses();
int index = 0;
while (ipAddresses.hasMoreElements()) {
InetAddress address = (InetAddress) ipAddresses.nextElement();
if (!address.isLinkLocalAddress()) {
break;
}
index++;
}
int prfLen = networkInterface.getInterfaceAddresses().get(index).getNetworkPrefixLength();
int shft = 0xffffffff << (32 - prfLen);
int oct1 = ((byte) ((shft & 0xff000000) >> 24)) & 0xff;
int oct2 = ((byte) ((shft & 0x00ff0000) >> 16)) & 0xff;
int oct3 = ((byte) ((shft & 0x0000ff00) >> 8)) & 0xff;
int oct4 = ((byte) (shft & 0x000000ff)) & 0xff;
subnetMask = oct1 + "." + oct2 + "." + oct3 + "." + oct4;
} catch (Exception e) {
log.debug("Error while getting Interface network mask by index");
return subnetMask;
}
return subnetMask;
}
/**
*
* @param s
* @return List of NetworkInterface
*/
private java.util.List parseInterfaceList(String s) throws Exception {
java.util.List interfaces=new ArrayList(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(interfaces.contains(intf)) {
log.warn("did not add interface " + interface_name + " (already present in " + print(interfaces) + ")");
}
else {
interfaces.add(intf);
}
}
return interfaces;
}
private static boolean isCoordinatorCoLocate(StreamMetadataStore streamMetadataStore) {
try {
Node coordinatorNode = streamMetadataStore.getCoordinatorNode();
if (coordinatorNode == null) {
logger.warn("no coordinator node registered");
return false;
}
InetAddress inetAddress = InetAddress.getByName(coordinatorNode.getHost());
return NetworkInterface.getByInetAddress(inetAddress) != null;
} catch (Exception e) {
logger.error("Error when check network interface.", e);
}
return true;
}
/**
* The user-id portion of Vault's app-auth should be machine specific and at least
* somewhat obfuscated to make it more difficult to derive. We use the sha256 hash of
* the MAC address of the first interface found by InetAddress.getLocalHost().
*
* This provides a way for administrators to compute the value itself during/after
* deployment and authorize the app-id, user-id pair out of band.
*
* @return String representation of the user-id portion of an auth token.
*/
static String calculateUserId(String csId) {
try {
// Try to hash based on default interface
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface netIf = NetworkInterface.getByInetAddress(ip);
byte[] mac = netIf.getHardwareAddress();
if (mac == null) {
// In some cases the default interface may be a tap/tun device which has no MAC
// instead pick the first available interface.
Enumeration<NetworkInterface> netIfs = NetworkInterface.getNetworkInterfaces();
while (netIfs.hasMoreElements() && mac == null) {
netIf = netIfs.nextElement();
mac = netIf.getHardwareAddress();
}
}
if (mac == null) {
throw new IllegalStateException("Could not find network interface with MAC address.");
}
Hasher hasher = HASH_FUNCTION.newHasher(6); // MAC is 6 bytes.
return hasher.putBytes(mac).hash().toString();
} catch (IOException e) {
LOG.error("CredentialStore '{}' Vault, could not compute Vault user-id: '{}'", csId, e);
throw new VaultRuntimeException("Could not compute Vault user-id: " + e.toString());
}
}
public static boolean isThisMyIpAddress(InetAddress addr) {
// Check if the address is a valid special local or loop back
if (addr.isAnyLocalAddress() || addr.isLoopbackAddress())
return true;
// Check if the address is defined on any interface
try {
return NetworkInterface.getByInetAddress(addr) != null;
} catch (SocketException e) {
return false;
}
}
/**
* Method that searches for and returns the network interface having
* the specified <code>name</code>.
*
* @param name <code>String</code> referencing the name of the
* network interface to return (for example, typical
* values for this parameter might be, "eth0", "eth1",
* "hme01", "lo", etc., depending on how the underlying
* platform is configured).
*
* @return an instance of <code>NetworkInterface</code> that represents
* the network interface corresponding to the given
* <code>name</code>, or <code>null</code> if there is no
* network interface with that name value.
*
* @throws SocketException if there is an error in the underlying
* I/O subsystem and/or protocol.
*
* @throws NullPointerException if <code>null</code> is input for
* <code>name</code>.
*/
public static NetworkInterface getNetworkInterface(String name)
throws SocketException
{
NetworkInterface nic = NetworkInterface.getByName(name);
if (nic == null) {
// try by IP address
InetAddress targetIp = null;
try {
targetIp = InetAddress.getByName(name);
nic = NetworkInterface.getByInetAddress(targetIp);
} catch (UnknownHostException uhe) {
// ignore, return null
}
}
return nic;
}
@Override
protected DatagramConnection getConnection(String remoteAddr, int port,
String interfaceAddress) throws FastConnectionException {
try {
NetworkInterface netIface = null;
if(StringUtils.isNotEmpty(interfaceAddress)) {
if (interfaceAddress.matches("([0-9]{1,3}\\.){3}[0-9]{1,3}")) {
netIface = NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceAddress));
} else {
netIface = NetworkInterface.getByName(interfaceAddress);
}
}
MulticastSocket socket = new MulticastSocket(port);
InetAddress groupAddress = InetAddress.getByName(remoteAddr);
if (netIface == null){
socket.joinGroup(groupAddress);
} else {
socket.joinGroup(
new InetSocketAddress(groupAddress,port),
netIface
);
}
this.datagramConnection = new DatagramConnection(
socket,
groupAddress,
getSettings().isStreamBlockEncoded(),
new IPacketHandler() {
@Override
public void handlePacket(byte[] packetData) {
if (resetContext) {
getReceiveContext().reset();
}
}
}
);
return datagramConnection;
} catch (IOException e) {
FastConnectionException expt = new FastConnectionException(
"Failed to create connection"
);
expt.initCause(e);
throw expt;
}
}
@Override
public void connect() throws Exception {
String interfaceIp = getSettings().getInterfaceIp();
String mcastIp = getSettings().getMulticastIp();
int mcastPort = getSettings().getMulticastPort();
this.localNetworkInterface = NetworkInterface.getByInetAddress(InetAddress.getByName(interfaceIp));
if (localNetworkInterface == null) {
throw new ServiceException("Failed to resolve network interface via IP: " + interfaceIp);
}
this.multicastGroup = new InetSocketAddress(InetAddress.getByName(mcastIp), mcastPort);
Bootstrap cb = new Bootstrap();
cb.group(nioEventLoopGroup);
cb.channelFactory(new NettyChannelFactory());
cb.option(ChannelOption.SO_REUSEADDR, true);
cb.option(ChannelOption.IP_MULTICAST_IF, localNetworkInterface);
cb.option(ChannelOption.IP_MULTICAST_TTL, getSettings().getTtl());
cb.localAddress(new InetSocketAddress(InetAddress.getByName(mcastIp), mcastPort));
cb.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
cb.handler(NOOP_CHANNEL_INITIALIZER);
Channel localChannel = cb.bind().addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture bindFuture) throws Exception {
if (!bindFuture.isSuccess()) {
return;
}
DatagramChannel channel = (DatagramChannel)bindFuture.channel();
ChannelFuture future;
String sourceIP = getSettings().getSourceIp();
if (sourceIP == null) {
future = channel.joinGroup(multicastGroup, localNetworkInterface);
} else {
future = channel.joinGroup(multicastGroup.getAddress(), localNetworkInterface, InetAddress.getByName(sourceIP));
}
future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}
}).addListener(ChannelFutureListener.CLOSE_ON_FAILURE).syncUninterruptibly().channel();
mainSession = createSession(localChannel);
mainSession.withWriteLock(this::initChannel);
mainSession.withWriteLock(this::initChannelCloseFuture);
}
@Test
public void testIsSoftwareVirtualAdapter() throws SocketException {
InetAddress inetAddress = LocalAddressUtils.getLoopbackAddress(IpAddressUtils.IpTypePreference.ANY_IPV4_PREF);
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
assertFalse(LocalAddressUtils.isSoftwareVirtualAdapter(networkInterface));
}