Android IP address with java

后端 未结 3 2033
春和景丽
春和景丽 2021-01-07 05:38

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 ope

3条回答
  •  孤街浪徒
    2021-01-07 05:57

    If you just need the IP for the Wifi connection you can retrieve the IP as a 32 bit integer:

    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    int ip = 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.

提交回复
热议问题