Android Ip Address With Java
I'm writing an Android video game that supports multiplayer. There is a dedicated server running which the androids connect to when the multiplayer button is clicked by opening a s
Solution 1:
If you just need the IP for the Wifi connection you can retrieve the IP as a 32 bit integer:
WifiManagerwifiManager= (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfowifiInfo= wifiManager.getConnectionInfo();
intip= wifiInfo.getIpAddress();
Then, in order to construct the IP in dot-decimal notation; bit-shift and mask the result:
String ipString = String.format(
"%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
android.permission.ACCESS_WIFI_STATE permission will be required in the manifest.
Solution 2:
Do you have to rely on the host to figure out its own IP address and provide this to the server? If the host opens a connection and sends a message to the server announcing that it is hosting a game, then could the server use the IP address that the connection and message came from? This would avoid the problem altogether.
Solution 3:
try this
WifiManager wim= (WifiManager) getSystemService(WIFI_SERVICE) ;
List<WifiConfiguration> l= wim.getConfiguredNetworks();
WifiConfiguration wc=l.get(0);
textview.append( "\n"+Formatter.formatIpAddress(wim.getConnectionInfo().getIpAddress()));
Post a Comment for "Android Ip Address With Java"