Android IP address with java

后端 未结 3 2034
春和景丽
春和景丽 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.

    0 讨论(0)
  • 2021-01-07 06:10

    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()));
    
    0 讨论(0)
  • 2021-01-07 06:15

    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.

    0 讨论(0)
提交回复
热议问题