Java判断局域网IP
在Java中判断一个IP地址是否属于局域网是一个常见的需求。本文将指导刚入行的小白如何实现这个功能。
流程
首先,我们来看一下整个判断局域网IP的流程。可以用以下表格展示:
步骤 | 描述 |
---|---|
步骤1 | 获取本机IP地址 |
步骤2 | 获取子网掩码 |
步骤3 | 判断IP地址是否属于局域网 |
接下来,我们将逐步介绍每一步需要做什么,并提供相应的代码。
步骤1:获取本机IP地址
首先,我们需要获取本机的IP地址。可以使用Java的InetAddress
类来实现。以下是示例代码:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetLocalIPAddress {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();
System.out.println("本机IP地址:" + ipAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
代码解释:
InetAddress.getLocalHost()
:获取本机的InetAddress对象。localHost.getHostAddress()
:获取本机的IP地址。
步骤2:获取子网掩码
接下来,我们需要获取子网掩码。同样地,我们可以使用InetAddress
类来实现。以下是示例代码:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class GetSubnetMask {
public static void main(String[] args) {
try {
InetAddress localHost = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
InterfaceAddress interfaceAddress = networkInterface.getInterfaceAddresses().get(0);
short prefixLength = interfaceAddress.getNetworkPrefixLength();
System.out.println("子网掩码:" + calculateSubnetMask(prefixLength));
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
}
private static String calculateSubnetMask(short prefixLength) {
int mask = 0xffffffff << (32 - prefixLength);
int[] bytes = new int[4];
bytes[0] = mask >> 24 & 0xff;
bytes[1] = mask >> 16 & 0xff;
bytes[2] = mask >> 8 & 0xff;
bytes[3] = mask & 0xff;
return bytes[0] + "." + bytes[1] + "." + bytes[2] + "." + bytes[3];
}
}
代码解释:
NetworkInterface.getByInetAddress(localHost)
:根据本机的InetAddress对象获取对应的NetworkInterface对象。networkInterface.getInterfaceAddresses().get(0)
:获取第一个接口地址,通常是IPv4地址。interfaceAddress.getNetworkPrefixLength()
:获取网络前缀长度,即子网掩码的位数。calculateSubnetMask()
:根据网络前缀长度计算子网掩码。
步骤3:判断IP地址是否属于局域网
现在,我们已经获得了本机的IP地址和子网掩码。最后一步是判断给定的IP地址是否属于局域网。以下是示例代码:
public class IsLocalIPAddress {
public static void main(String[] args) {
String ipAddress = "192.168.0.100"; // 需要判断的IP地址
String subnetMask = "255.255.255.0"; // 子网掩码
boolean isLocal = isLocalIPAddress(ipAddress, subnetMask);
System.out.println("IP地址是否属于局域网:" + isLocal);
}
private static boolean isLocalIPAddress(String ipAddress, String subnetMask) {
try {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
InetAddress subnetInetAddress = InetAddress.getByName(subnetMask);
byte[] ipBytes = inetAddress.getAddress();
byte[] subnetBytes = subnetInetAddress.getAddress();
for (int i = 0; i < 4; i++) {
if ((ipBytes[i] & subnetBytes[i]) != (subnetBytes[i] & 0xff)) {
return false;
}
}
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
}
}
代码解释:
InetAddress.getByName(ipAddress)
:根据给定的IP地址获取对应的InetAddress对象。