Click here to Skip to main content
15,886,773 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I've tired to get exact ethernet ip address.

Java
InetAddress ip=InetAddress.getLocalHost();
String iaddr = ip.getHostAddress();


It return localhost address only. I need ethernet address only..

pls help me..
Posted
Updated 3-Oct-12 19:51pm
v2

You are pretty close - just a bit more coding to make it visible:
Try this:

Java
public static void main(String[] args) {
		
		try {
		    InetAddress addr = InetAddress.getLocalHost();

		    // Get IP Address
		    byte[] ipAddr = addr.getAddress();

		    // Get hostname
		    String hostname = addr.getHostName();
		    System.out.println("hostname " + hostname);
		    System.out.println("IP Address " + convertIP(ipAddr));
		} catch (java.net.UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	// Convert to dot representation
	private static String convertIP(byte[] ipAddr){
	    String ipAddrStr = "";
	    for (int i=0; i<ipAddr.length; i++) {
	        if (i > 0) {
	            ipAddrStr += ".";
	        }
	        ipAddrStr += ipAddr[i]&0xFF;
	    }
	    return ipAddrStr;
	}
 
Share this answer
 
v4
Comments
TorstenH. 4-Oct-12 5:39am    
Questioners Comment:
host name only printed... not returning ip.
TorstenH. 4-Oct-12 5:40am    
That code returns the IP-Address and the host name here - does it fail on your machine?
hari301 8-Oct-12 14:45pm    
ya it failed.. still i dont't know how to get..?
TorstenH. 8-Oct-12 14:48pm    
switch off firewall.
Quote:
The following code working on Linux(ubuntu).. If u have to use on windows, just change the "ppp0" to "ppp2". surely it will return the internet IP Address.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import javax.swing.JOptionPane;

public class ShowIp {

    public static void main(String[] args) throws SocketException {
        NetworkInterface ni = NetworkInterface.getByName("ppp0");
        Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();


        while (inetAddresses.hasMoreElements()) {
            InetAddress ia = inetAddresses.nextElement();
            if (!ia.isLinkLocalAddress()) {
                JOptionPane.showMessageDialog(null, ia.getHostAddress());
            }
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900