IP Address of mobile phone using Java ME/ J2ME

There are many situations where you may want to know your phone's IP Address. You know that your mobile connects over GPRS which in turn is based on Internet Protocol, so you are pretty confident that the phone has an IP Address.
Well then, there is a good news and a bad news for you. The good news is that your phone do have an IP Address. The bad news is that this IP address will be hardly usefull for you. Why? read on.



The above image shows the network layout of most mobile based IP connection. Your mobile handset will be connected to the service provider's NAT gateway. The IP that your mobile handset get is a private IP, means that this IP can't be reached from external world.

There are ways to get both your private IP and the IP Address of the NAT gateway.

Getting your IP Address
1)The following snippet will give you your private IP Address.


ServerSocketConnection scn = (ServerSocketConnection)Connector.open("socket://:1234");
System.out.println(scn.getLocalAddress());


Note: This method may return your IP Address as 127.0.0.1 (the loopback address) if the GPRS link has been idle. So always send some data over the connection before testing this.

2)Using the System properties

System.getProperty("microedition.hostname");

This is supposed to give you the IP Address. But for me this returns 127.0.0.1 always. If you had any success with this, please share in the comments.

3)This is a bit round about method, but is the most guarenteed to work one. If you are trying to connect to your custom server, have the server tell your ip to you. Implement a handshake protocol, where you say "Hello server" and the server replies "Hello client. Your IP is xx.xx.xx.xx".

Getting the IPAddress of the NAT gateway

Service like http://whatismyipaddress.com/ or http://www.lawrencegoetz.com/programs/ipinfo/ or http://www.whatismyip.com/ gives the IP Address it sees when you browse their pages. This will be your NAT IP Address. Just parse the page and get the IP.

Remember all these works only if you are using GPRS/Wifi. If you want to know the IP address it need to be a IP based network.
If all you want is a unique number to identify your mobile, read this post on using IMEI number

Post your success stories and failure in the comments. Let me know how much this post helped you.