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();
        }
LVL 5
stef4sAsked:
Who is Participating?
 
Computer101Connect With a Mentor Commented:
PAQed with points refunded (250)

Computer101
EE Admin
0
 
brunoguimaraesCommented:
Have you tried using java.net.Inet4Address class?

http://java.sun.com/j2se/1.5/docs/api/java/net/Inet4Address.html
0
 
stef4sAuthor Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.