下面列出了java.net.NetworkInterface#getName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static InetAddress readCrossSystemIPv4Address() {
try {
Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) networkInterfaces.nextElement();
String name = ni.getName();
if (!name.contains("docker") && !name.contains("lo")) {
Enumeration ipEnum = ni.getInetAddresses();
while (ipEnum.hasMoreElements()) {
InetAddress addr = (InetAddress) ipEnum.nextElement();
if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress() && addr instanceof Inet4Address) {
return addr;
}
}
}
}
} catch (Exception e) {
LOG.error(TxleConstants.logErrorPrefixWithTime() + "Failed to get the realistic address of current system.", e);
}
return null;
}
String getLinuxLocalIp(Logger log) {
String ip = "127.0.0.1";
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
String name = intf.getName();
if (!name.contains("docker") && !name.contains("lo")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String ipaddress = inetAddress.getHostAddress().toString();
if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
ip = ipaddress;
}
}
}
}
}
} catch (SocketException ex) {
log.warn("get ip failed", ex);
}
log.info("Send IP:" + ip);
return ip;
}
private void setVpnInterfaceName(NetworkInterface intf) throws SocketException {
if (!intf.isPointToPoint()) {
return;
}
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
String hostAddress = inetAddress.getHostAddress();
if (hostAddress.contains(addressVPN)) {
vpnInterfaceName = intf.getName();
Log.i(LOG_TAG, "VPN interface name " + vpnInterfaceName);
}
}
}
@Test
public void testBasic() throws Exception {
if (allCandidates.size() < 1) {
return;
}
for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : allCandidates.entrySet()) {
NetworkInterface nic = entry.getKey();
String target = nic.getName();
NicInterfaceCriteria testee = new NicInterfaceCriteria(target);
Map<NetworkInterface, Set<InetAddress>> result = testee.getAcceptableAddresses(allCandidates);
assertEquals(1, result.size());
Set<InetAddress> addresses = result.get(nic);
assertNotNull(addresses);
// WFLY-786 NicInterfaceCriteria doesn't prune based on IPv6/v4 preference
// so we shouldn't test that it does. Pruning is done by OverallInterfaceCriteria
// Set<InetAddress> rightType = getRightTypeAddresses(entry.getValue());
// assertEquals(rightType, addresses);
// assertTrue(addresses.containsAll(rightType));
}
}
/**
* IP アドレスを取得して、各変数に格納します.
*/
public void storeIPAddress() {
Enumeration<NetworkInterface> enumeration;
try {
enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface netIf = enumeration.nextElement();
Enumeration<InetAddress> ipAddrs = netIf.getInetAddresses();
while (ipAddrs.hasMoreElements()) {
InetAddress inetAddress = ipAddrs.nextElement();
if (!inetAddress.isLoopbackAddress() && netIf.isUp()) {
String networkInterfaceName = netIf.getName();
if (DEBUG) {
Log.d(TAG, networkInterfaceName + ": " + inetAddress);
}
setIPAddress(inetAddress, networkInterfaceName);
}
}
}
} catch (SocketException e) {
if (DEBUG) {
Log.e(TAG, "", e);
}
}
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
public void printLocalIpAddresses(){
String s="";
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(!intf.isLoopback()){
s+="Interface "+intf.getName()+": "+inetAddress.getHostAddress()+"\n";
}
}
}
makeText(s,mTextView3);
}catch(Exception e){e.printStackTrace();}
}
private boolean isAnotherVpnActive() {
if (VERSION.SDK_INT >= VERSION_CODES.M) {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
Network activeNetwork = connectivityManager.getActiveNetwork();
if (activeNetwork == null) {
return false;
}
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(activeNetwork);
if (capabilities == null) {
// It's not clear when this can happen, but it has occurred for at least one user.
return false;
}
return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
}
// For pre-M versions, return true if there's any network whose name looks like a VPN.
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
String name = networkInterface.getName();
if (networkInterface.isUp() && name != null &&
(name.startsWith("tun") || name.startsWith("pptp") || name.startsWith("l2tp"))) {
return true;
}
}
} catch (SocketException e) {
LogWrapper.logException(e);
}
return false;
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
private String checkIpAddress(String ipAddress, boolean checkForLocalhost) {
Enumeration<NetworkInterface> ifs = null;
try {
ifs = NetworkInterface.getNetworkInterfaces();
} catch(SocketException e) {
log.error("checkIpAddress cannot get ip address of this host, Exiting with message: " + e.getMessage(), e);
return null;
}
String addressString = null;
InetAddress address = null;
while (ifs.hasMoreElements() && addressString == null) {
NetworkInterface xface = ifs.nextElement();
Enumeration<InetAddress> addrs = xface.getInetAddresses();
String name = xface.getName();
int IPsPerNic = 0;
while (addrs.hasMoreElements() && IPsPerNic == 0) {
address = addrs.nextElement();
if (InetAddressUtils.isIPv4Address(address.getHostAddress())) {
log.debug(name + " ... has IPV4 addr " + address);
if(checkForLocalhost && (!name.equalsIgnoreCase(Configuration.LOOP_BACK_INTERFACE) || !address.getHostAddress().equalsIgnoreCase(Configuration.LOOP_BACK_ADDRESS))) {
IPsPerNic++;
addressString = address.getHostAddress();
log.debug("checkIpAddress found " + addressString + " from interface " + name);
}
else if(ipAddress != null && ipAddress.equalsIgnoreCase(address.getHostAddress())){
addressString = ipAddress;
IPsPerNic++;
}
}
}
}
return addressString;
}
@Override
public boolean apply(NetworkInterface iface) {
String name = iface.getName();
if (!names.contains(name)) {
LOG.debug("Ignoring NetworkInterface: Not included by name: {} in {}", name, names);
return false;
}
return super.apply(iface);
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
/**
* 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);
if (interf == null) {
throw new JdpException("Unable to get network interface for " + srcAddress.toString());
}
if (!interf.isUp()) {
throw new JdpException(interf.getName() + " is not up.");
}
if (!interf.supportsMulticast()) {
throw new JdpException(interf.getName() + " does not support multicast.");
}
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);
}
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
private static CharSequence getZone(Inet6Address inet6Address) {
NetworkInterface networkInterface = inet6Address.getScopedInterface();
String zone = null;
if(networkInterface == null) {
int scopeId = inet6Address.getScopeId();
if(scopeId != 0) {
zone = Integer.toString(scopeId);
}
} else {
zone = networkInterface.getName();
}
return zone;
}
static void assertNetworkInterfaceNameEqual(String expectedNetworkIfName,
NetworkInterface deserializedNetworkInterface) {
if (deserializedNetworkInterface != null) {
String deserializedNetworkIfName = deserializedNetworkInterface
.getName();
System.err
.println("Inet6AddressSerializationTest.assertHostNameEqual:");
if (expectedNetworkIfName == null) {
if (deserializedNetworkIfName == null) {
// ok, do nothing.
} else {
System.err.println("Error checking "
+ " NetworkIfName, expected: "
+ expectedNetworkIfName + ", got: "
+ deserializedNetworkIfName);
failed = true;
}
} else if (!expectedNetworkIfName.equals(deserializedNetworkIfName)) {
System.err.println("Error checking "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
failed = true;
} else {
System.err.println("NetworkIfName equality "
+ " NetworkIfName, expected: " + expectedNetworkIfName
+ ", got: " + deserializedNetworkIfName);
}
} else {
System.err
.println("Warning "
+ " NetworkInterface expected, but is null - ifname not relevant on deserializing host");
}
}
void setInterfaceNames() {
final String addressesRangeUSB = "192.168.42.";
final String addressesRangeWiFi = "192.168.43.";
usbTetherOn = false;
ethernetOn = false;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
if (intf.isLoopback()) {
continue;
}
if (intf.isVirtual()) {
continue;
}
if (!intf.isUp()) {
continue;
}
setVpnInterfaceName(intf);
if (intf.isPointToPoint()) {
continue;
}
if (intf.getHardwareAddress() == null) {
continue;
}
if (intf.getName().replaceAll("\\d+", "").equalsIgnoreCase("eth")) {
ethernetOn = true;
ethernetInterfaceName = intf.getName();
Log.i(LOG_TAG, "LAN interface name " + ethernetInterfaceName);
}
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
String hostAddress = inetAddress.getHostAddress();
if (hostAddress.contains(addressesRangeWiFi)) {
this.apIsOn = true;
wifiAPInterfaceName = intf.getName();
Log.i(LOG_TAG, "WiFi AP interface name " + wifiAPInterfaceName);
}
if (hostAddress.contains(addressesRangeUSB)) {
usbTetherOn = true;
usbModemInterfaceName = intf.getName();
Log.i(LOG_TAG, "USB Modem interface name " + usbModemInterfaceName);
}
}
}
} catch (SocketException e) {
Log.e(LOG_TAG, "Tethering SocketException " + e.getMessage() + " " + e.getCause());
}
if (usbTetherOn && !new PrefManager(context).getBoolPref("ModemIsON")) {
new PrefManager(context).setBoolPref("ModemIsON", true);
ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
} else if (!usbTetherOn && new PrefManager(context).getBoolPref("ModemIsON")) {
new PrefManager(context).setBoolPref("ModemIsON", false);
ModulesStatus.getInstance().setIptablesRulesUpdateRequested(context, true);
}
}
private static String getInterfaceName(NetworkInterface networkInterface) {
if (networkInterface != null) {
return networkInterface.getName();
}
return "";
}