要在同一网络(子网)中使用Java获取连接的IP列表,您可以使用以下方法:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPAddressExample {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("本地IP地址:" + ip.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SubnetMaskExample {
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ip);
int subnetMask = 0;
for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
if (address.getAddress().getHostAddress().equals(ip.getHostAddress())) {
subnetMask = address.getNetworkPrefixLength();
break;
}
}
System.out.println("子网掩码:" + subnetMask);
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
}
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class NetworkIPAddressesExample {
public static void main(String[] args) {
List<String> ipAddresses = new ArrayList<>();
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ip);
int subnetMask = 0;
for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
if (address.getAddress().getHostAddress().equals(ip.getHostAddress())) {
subnetMask = address.getNetworkPrefixLength();
break;
}
}
int networkPrefixLength = subnetMask;
int addressLength = ip.getAddress().length;
byte[] networkAddress = new byte[addressLength];
byte[] subnetMaskBytes = new byte[addressLength];
for (int i = 0; i< addressLength; i++) {
networkAddress[i] = (byte) (ip.getAddress()[i] & (subnetMask >= 8 ? 0xFF : (1<< subnetMask) - 1));
subnetMaskBytes[i] = (byte) (subnetMask >= 8 ? 0xFF : (1<< subnetMask) - 1);
subnetMask -= 8;
}
InetAddress network = InetAddress.getByAddress(networkAddress);
InetAddress broadcast = InetAddress.getByAddress(subnetMaskBytes);
System.out.println("网络地址:" + network.getHostAddress());
System.out.println("广播地址:" + broadcast.getHostAddress());
for (int i = 1; i < 255; i++) {
InetAddress address = InetAddress.getByAddress(new byte[]{networkAddress[0], networkAddress[1], networkAddress[2], (byte) i});
if (!address.getHostAddress().equals(ip.getHostAddress())) {
ipAddresses.add(address.getHostAddress());
}
}
System.out.println("网络中的IP地址列表:");
ipAddresses.forEach(System.out::println);
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
}
这个示例代码将获取本地IP地址、子网掩码、网络地址和广播地址,并输出网络中的所有IP地址列表。请注意,这个示例代码仅适用于小型网络,因为它只检查了1到254之间的IP地址。对于大型网络,您可能需要使用其他方法来扫描网络中的所有IP地址。
领取专属 10元无门槛券
手把手带您无忧上云