Link to home
Start Free TrialLog in
Avatar of stef4s
stef4s

asked on

getting ipv4 address from dual stack ipv6 and ipv4 host

Hi all

using Java 1.5.0_09

On windows vista (which has a dual stack IPv4 and IPv6 installed) using the code (below) only reveals the Ipv6 hostAddress. I need the IPv4 hostAddress.
Please assist

Enumeration NetEnum;
        StringBuilder buff = new StringBuilder();
        try {
           
            NetEnum = NetworkInterface.getNetworkInterfaces();
            Enumeration InetEnum = null;
            NetworkInterface MyNet = null;
            InetAddress MyInet  = null;
            while(NetEnum.hasMoreElements()){
                MyNet = (NetworkInterface) NetEnum.nextElement();
                InetEnum =  MyNet.getInetAddresses();
               
                buff.append(MyNet.getDisplayName()+"\n");
                while(InetEnum.hasMoreElements()){
                    MyInet = (InetAddress) InetEnum.nextElement();
                   
                    if(!MyInet.getHostName().equals("localhost")){
                        mHostName = MyInet.getHostName();
                        mHostAddress =  MyInet.getHostAddress();
                        mInetAddress = MyInet;
                    }
                    buff.append(MyInet.getHostName() + " " + MyInet.getHostAddress()+"\n");
                    //System.out.println(MyInet.getHostName() + " " + MyInet.getHostAddress());
                }                
            }
            //log.info(buff.toString());
            log.info("localhost: "+ mHostName + " " + mHostAddress);
           
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
Avatar of brunoguimaraes
brunoguimaraes
Flag of Brazil image

Have you tried using java.net.Inet4Address class?

http://java.sun.com/j2se/1.5/docs/api/java/net/Inet4Address.html
Avatar of stef4s
stef4s

ASKER

Yes I have. unfortunately when trying to convert addresses i get a Casting exception.

I have however found a way to get the ipv4 address. (I don't understand why the code below returns a ipv4 address)

So the solution is

        try
        {
            InetAddress ia = InetAddress.getLocalHost();
            mHostName = ia.getHostName();
            mHostAddress = ia.getHostAddress();
            mInetAddress = ia;
            log.info("IP", mInetAddress);
           
        }
        catch (UnknownHostException e)
        {
            //System.out.println("oops, couldn't get localhost");
            log.error("could not get localhost");
        }

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial