Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

How to get IP address?

  Asked By: Cameron    Date: May 22    Category: Java    Views: 2923

Can you help me. I want to know how to get my own IP address (but not
localhost) from my computer using java. I tried using InetAddress
but my application can't compiled. The message was something about
static method : "static method getAddress() (or maybe getHostAddress
()) cannot be referenced from static context myMethod()"
Can anyone help me with this???

One more question. If I have a client-server application using RMI,
how can I send messages to all client, and how can I disconnect my
client?? I've been looking through the web, but I haven't found any.



2 Answers Found

Answer #1    Answered By: Dominic Murphy     Answered On: May 22

public static  String IP()
String ip = "";
String hostName = InetAddress.getLocalHost().getHostName();
InetAddress[] ipList = InetAddress.getAllByName(hostName);
for(int i = 0;i < ipList.length;i++)
ip = ipList[i].getHostAddress();
catch(Exception e)
return ip;

Answer #2    Answered By: Silk Choco     Answered On: Apr 03

Use the following code to find your ip address:

public class NetInfo {
public static void main(String[] args) {
new NetInfo().say();

public void say() {
try {
java.net.InetAddress i = java.net.InetAddress.getLocalHost();
System.out.println(i); // name and IP address
System.out.println(i.getHostName()); // name
System.out.println(i.getHostAddress()); // IP address only
catch(Exception e){e.printStackTrace();}


To send message to client and disconnect, use the link stackoverflow.com/.../how-can-i-get-my-java-chat-client-and-server-to-exchange-messages-from-a-textfie . If you want to view your external ip address visit http://www.ip-details.com/ .

Didn't find what you were looking for? Find more on How to get IP address? Or get search suggestion and latest updates.