fix unexpect exception from NetworkInterface.ifUp (#12325)

This commit is contained in:
shalk(xiao kun) 2024-07-10 16:52:23 +08:00 committed by GitHub
parent 8aba80d3c1
commit 2aa9fc51bc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 36 additions and 4 deletions

View File

@ -32,6 +32,7 @@ import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Enumeration;
@ -192,12 +193,12 @@ public class InetUtils {
for (Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
nics.hasMoreElements(); ) {
NetworkInterface ifc = nics.nextElement();
if (ifc.isUp()) {
if (isUp(ifc)) {
LOG.debug("Testing interface: " + ifc.getDisplayName());
if (ifc.getIndex() < lowest || result == null) {
lowest = ifc.getIndex();
} else {
if (ifc.getIndex() >= lowest && result != null) {
continue;
} else {
lowest = ifc.getIndex();
}
if (!ignoreInterface(ifc.getDisplayName())) {
@ -231,6 +232,20 @@ public class InetUtils {
return null;
}
/**
* check network intreface isUp, not throw SocketException.
* @param ifc network interface
* @return true or false;
*/
public static boolean isUp(NetworkInterface ifc) {
try {
return ifc.isUp();
} catch (SocketException e) {
LOG.debug("Network interface can not get isUp, exception: ", e);
}
return false;
}
private static boolean isPreferredAddress(InetAddress address) {
if (useOnlySiteLocalInterface) {
final boolean siteLocalAddress = address.isSiteLocalAddress();

View File

@ -25,6 +25,8 @@ import org.junit.jupiter.api.Test;
import org.springframework.mock.env.MockEnvironment;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.sys.env.Constants.NACOS_SERVER_IP;
@ -32,6 +34,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class InetUtilsTest {
@ -71,4 +75,17 @@ class InetUtilsTest {
assertNotNull(address);
assertFalse(address.isLoopbackAddress());
}
@Test
void testisUp() throws SocketException {
NetworkInterface nic = mock(NetworkInterface.class);
when(nic.isUp()).thenReturn(true);
assertTrue(InetUtils.isUp(nic));
when(nic.isUp()).thenReturn(false);
assertFalse(InetUtils.isUp(nic));
when(nic.isUp()).thenThrow(new SocketException());
assertFalse(InetUtils.isUp(nic));
}
}