Wednesday, May 26, 2010

How to get client IP address in Applet

You can use the following example to get the client IP address in Applet.
The process is not so straightforward, you have to get the current host
and port from where Applet is loaded, and convert it to Socket object.



Socket
socket = new Socket(getDocumentBase().getHost(), port);
ip = socket.getLocalAddress().getHostAddress();


package
com.mkyong.applet;
 
import java.applet.*;
import java.awt.Graphics;
import java.io.IOException;
import java.net.Socket;
 
public class AppletExample extends Applet {
 
String ip;
 
public void init() {
 
try{
int port;
 
if(getDocumentBase().getPort()!=-1){
port = getDocumentBase().getPort();
}else{
port = 80;
}
 
Socket socket = new Socket(getDocumentBase().getHost(), port);
ip = socket.getLocalAddress().getHostAddress();
 
}catch(IOException io){
System.out.println(io.getMessage());
}
}
 
public void paint( Graphics g ) {
 
StringBuffer sb = new StringBuffer()
.append(" IP address : ").append(ip);
 
g.drawString(sb.toString(), 0,100);
}
 
}

No comments:

Post a Comment