Symbian
Symbian OS Library

FAQ-0762 java.net.InetAddress.getLocalHost() doesn't get my IP address like it should.

[Index][spacer] [Previous] [Next]



 

Classification: Java Category: java.net
Created: 01/09/2002 Modified: 01/17/2002
Number: FAQ-0762
Platform: ER5, Symbian OS v6.0, Symbian OS v6.1

Question:
When the following class is run on Symbian OS, it prints out "localhost/127.0.0.1" whether or not an Internet connection has been made. Why is this?
public class getLocalHost {
public static void main (String[] args) {
try {
System.out.println (java.net.InetAddress.getLocalHost());
}
catch (Exception e) {
System.out.println (e.getMessage());
}
}
}


Answer:
This is a limitation of pJava on Symbian OS. The implementation of the getLocalHost() method inherited from Sun's shared code does DNS lookup against the phone's host name. This strategy is problematic in the first place because, if an Internet connection has not yet been established, no host name will be found, "localhost" will be substituted and 127.0.0.1 returned.

    But there is a further problem in that, on Symbian OS, even if an Internet connection is established, a defect results in no host name being reported and 127.0.0.1 is still returned.

    The work around for this problem is to open a socket and use the alternative socket-based API which allows the local IP address to be extracted as follows:
    try
    {
    Socket socket = new Socket("www.symbian.com", 80);
    InetAddress localhost = socket.getLocalAddress();
    System.out.println("Address of local host is " + localhost);
    socket.close();
    }
    catch(Exception e)
    {
    System.out.println("Exception: " + e.getMessage());
    }

    This strategy successfully returns the local IP address even when no prior Internet connection has been established: the instantiation of the new Socket precipitates the connection.

    Unfortunately a defect in Symbian OS v5, fixed for v6.0, prevents even this from working. In that case a JNI-based utility class com.symbian.devnet.util.Inet provides a work around method, essentially using the above approach but instantiating the socket in native code. This work around for Symbian OS v5 can be obtained from http://www.symbian.com/developer/downloads/java_util.html.

    Note added 27/5/2002: The remote IP address used in the published version of the Inet class to force an Internet connection is no longer valid. The dlls provided therein should be replace by those in the attached zip, which connect instead to 212.134.93.203, the current IP address for www.symbian.com.