在我的Swing应用程序(使用Web-Start)中,我必须手动输入我想要访问应用程序的机器的IP地址,现在,在访问IP地址时,我要检查我输入的机器IP地址是否仅通过LAN (通过交换机,而不是路由器)连接到我的机器(充当本地服务器)。因为如果机器不在LAN中,它就不应该授予访问应用程序的权限。
我怎样才能做到这一点?
发布于 2012-04-01 06:17:44
据我了解您的问题,您需要检查输入到应用程序中的特定IP地址是否位于客户端主机的直接连接网络上。
如果是这样的话,那么使用普通ping将不适合您,因为ping将涉及数据包路由。所以就连路由器后面的主机也会回复。
作为解决办法,您可以在ping中添加‘-t1’参数,为ICMP数据包指定TTL,这样它们就不能通过路由器。
或者看看下面的示例,如果您希望这样的东西在java中实现(您应该根据您的需要采用它):
public class IsAddressDirectlyConnected {
private static class Network {
int network;
int mask;
Network(int n, int m) {
network = n;
mask = m;
}
};
// list of networks on interfaces of machine this code is being run on
List<Network> mDirectlyAttachedNetworks = new ArrayList<Network>();
private int addrBytesToInt(byte[] addr) {
int addri = 0;
for (int i = 0; i < addr.length; ++i)
addri = (addri << 8) | ((int)addr[i] & 0xFF);
return addri;
}
private void collectLocalAddresses() {
try {
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
if (nif.isUp()) {
List<InterfaceAddress> ias = nif.getInterfaceAddresses();
for (InterfaceAddress ia : ias) {
InetAddress ina = ia.getAddress();
if (ina instanceof Inet4Address) {
int addri = addrBytesToInt(ina.getAddress());
int mask = -1 << (32 - ia.getNetworkPrefixLength());
addri &= mask;
mDirectlyAttachedNetworks.add(new Network(addri, mask));
}
}
}
}
} catch (SocketException ex) {
System.err.println("Socket i/o error: " + ex.getLocalizedMessage());
}
}
public boolean isDirectlyAttachedAndReachable(InetAddress address) {
int checkedAddr = addrBytesToInt(address.getAddress());
try {
if (!address.isReachable(1000))
return false;
} catch (IOException ex) {
System.err.println("Failed to check reachability: " + ex.getLocalizedMessage());
return false;
}
for (Network n : mDirectlyAttachedNetworks) {
if ((checkedAddr & n.mask) == n.network)
return true;
}
return false;
}
public IsAddressDirectlyConnected() {
collectLocalAddresses();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
IsAddressDirectlyConnected iadc = new IsAddressDirectlyConnected();
if (args.length == 1) {
try {
boolean check = iadc.isDirectlyAttachedAndReachable(Inet4Address.getByName(args[0]));
System.out.println("Given IP is " + (check ? "" : "not ") + "on directly attached network " + (check ? "and " : "or not ") + "reachable from local host.");
} catch (UnknownHostException ex) {
System.err.println("Failed to parse address: " + ex.getLocalizedMessage());
}
} else System.out.println("Specify address to check.");
}
}
发布于 2012-04-01 03:11:30
只需按那个地址
Process p = Runtime.getRuntime().exec("ping " + your_ip_address);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
https://stackoverflow.com/questions/9963858
复制相似问题