JavaScript与Java Applet交互获取IP地址
本文通过一个小例子演示了如何通过js与JavaApplet的交互来获取IE端的IP地址
//java代码
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.applet.Applet;
public class MyIpApplet extends Applet{
private String ipAddress=null;
private String hostName=null;
public void init(){
try {
InetAddress localhost = InetAddress.getLocalHost();
ipAddress=localhost.getHostAddress());
hostName=localhost.getHostName());
}catch(UnknownHostException ex){
ipAddress="";
hostName="";
}
if(null==ipAddress){
ipAddress="";
}
if(null==hostName){
hostName="";
}
}
public String getIpAddress(){
return ipAddress;
}
public String getHostName(){
return hostName;
}
}
//html代码
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title></title>
</head>
<body>
<applet code="MyIpApplet.class" width="0" height="0" style="display:none; visibility:hidden">
</applet>
</body>
<script language="javascript">
var ipApplet=document.applets[0];
var ipAddress=ipApplet.getIpAddress();
var hostName=ipApplet.getHostName();
alert(ipAddress);
alert(hostName);
</script>
</html>
当从本地执行时,可以获得正确的Ip地址和主机名
但是当从服务器端下载后在IE里执行时,却总会获得127.0.0.1和localhost