Italian Ricerca di dispositivi IP nella rete wifi

Tomek92

Member
Licensed User
Come utilizzare la libreria Wifi Direct per trovare i dispositivi nella rete wifi? Vorrei visualizzare l'elenco degli indirizzi dei dispositivi sulla rete wifi.
 

Star-Dust

Expert
Licensed User
Longtime User
Io farei un ping in broadcasting
 

Tomek92

Member
Licensed User
Grazie per le tue risposte.
@LucaMs, intendi fare uno snippet java in un progetto b4a? Secondo questa guida?
https://www.google.com/amp/s/www.b4x.com/android/forum/threads/inline-java-code.50141/?amp=1

@Star-Dust, intendi un codice del genere?
B4X:
'Returns the UDP broadcast address.
'Returns an empty string if not available.
Sub GetBroadcastAddress As String
   Dim niIterator As JavaObject
   niIterator = niIterator.InitializeStatic("java.net.NetworkInterface").RunMethod("getNetworkInterfaces", Null)
   Do While niIterator.RunMethod("hasMoreElements", Null)
     Dim ni As JavaObject = niIterator.RunMethod("nextElement", Null)
     If ni.RunMethod("isLoopback", Null) = False Then
       Dim addresses As List = ni.RunMethod("getInterfaceAddresses", Null)
       For Each ia As JavaObject In addresses
         Dim broadcast As Object = ia.RunMethod("getBroadcast", Null)
         If broadcast <> Null Then
           Dim b As String = broadcast
           Return b.SubString(1)
         End If
       Next
     End If
   Loop
   Return ""
End Sub
 

Star-Dust

Expert
Licensed User
Longtime User
Grazie per le tue risposte.
@LucaMs, intendi fare uno snippet java in un progetto b4a? Secondo questa guida?
https://www.google.com/amp/s/www.b4x.com/android/forum/threads/inline-java-code.50141/?amp=1

@Star-Dust, intendi un codice del genere?
B4X:
'Returns the UDP broadcast address.
'Returns an empty string if not available.
Sub GetBroadcastAddress As String
   Dim niIterator As JavaObject
   niIterator = niIterator.InitializeStatic("java.net.NetworkInterface").RunMethod("getNetworkInterfaces", Null)
   Do While niIterator.RunMethod("hasMoreElements", Null)
     Dim ni As JavaObject = niIterator.RunMethod("nextElement", Null)
     If ni.RunMethod("isLoopback", Null) = False Then
       Dim addresses As List = ni.RunMethod("getInterfaceAddresses", Null)
       For Each ia As JavaObject In addresses
         Dim broadcast As Object = ia.RunMethod("getBroadcast", Null)
         If broadcast <> Null Then
           Dim b As String = broadcast
           Return b.SubString(1)
         End If
       Next
     End If
   Loop
   Return ""
End Sub
Si all'incirca
 

Tomek92

Member
Licensed User
@LucaMs
Potreste aiutarmi a inserire questo codice in un progetto vuoto? Ho aggiunto il codice e ho dei bug, non so se mancano ancora delle librerie.
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private NativeMe As JavaObject
    Private xui As XUI
    
    Dim udppack As UDPPacket    'zmienna jako UDPPacket do wysyłania
    Dim udp As UDPSocket        'zmienna jako UDPSocket
    Dim MyLan As ServerSocket    'do komunikacji TCP
    
 End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Dim matip As String                'zmienna przechowująca adres IP
    Dim matport As Int                'zmienna przechowująca adres port
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    
    matip = "192.168.1.17"        'wpisanie ip do zmiennej
    matport = 8899                'wpisanie portu do zmiennej
    
    If FirstTime Then
        NativeMe.InitializeContext
        MyLan.Initialize( "8899", "lan" )                    'inicjalizacja server socket
        udp.Initialize( "udpsrv", matport, 1024 )    'inicjalizacja UDP    ("udpsrv" - do zdarzenia odbiorczego, "" - bez zdarzenai obiorczego)
    End If
    
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then    'jeśli aplikacja zminimalizowana to
        Activity.Finish        'zakończ aplikację
        ExitApplication        'wyłącz aplikację
    End If
End Sub


Sub Button1_Click
    'Qui voglio chiamare una funzione java per visualizzare un elenco di indirizzi IP.
    NativeMe.RunMethod("NetworkSniffTask", Null)
End Sub


#If JAVA
static class NetworkSniffTask extends AsyncTask<Void, Void, Void> {

  private static final String TAG = Constants.TAG + "nstask";

  private WeakReference<Context> mContextRef;

  public NetworkSniffTask(Context context) {
    mContextRef = new WeakReference<Context>(context);
  }

  @Override
  protected Void doInBackground(Void... voids) {
    Log.d(TAG, "Let's sniff the network");

    try {
      Context context = mContextRef.get();

      if (context != null) {

        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);

        WifiInfo connectionInfo = wm.getConnectionInfo();
        int ipAddress = connectionInfo.getIpAddress();
        String ipString = Formatter.formatIpAddress(ipAddress);


        Log.d(TAG, "activeNetwork: " + String.valueOf(activeNetwork));
        Log.d(TAG, "ipString: " + String.valueOf(ipString));

        String prefix = ipString.substring(0, ipString.lastIndexOf(".") + 1);
        Log.d(TAG, "prefix: " + prefix);

        for (int i = 0; i < 255; i++) {
          String testIp = prefix + String.valueOf(i);

          InetAddress address = InetAddress.getByName(testIp);
          boolean reachable = address.isReachable(1000);
          String hostName = address.getCanonicalHostName();

          if (reachable)
            Log.i(TAG, "Host: " + String.valueOf(hostName) + "(" + String.valueOf(testIp) + ") is reachable!");
        }
      }
    } catch (Throwable t) {
      Log.e(TAG, "Well that's not good.", t);
    }

  return null;
}
#End If


@Star-Dust
Per l'esercizio, sto cercando di ottenere gli indirizzi IP disponibili dal pulsante, ma ne ottengo solo uno 192.168.1.255, non ne sono a conoscenza. Potresti per favore mostrare un esempio di come dovrei farlo correttamente?
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Private xui As XUI
    
    Dim udppack As UDPPacket    'zmienna jako UDPPacket do wysyłania
    Dim udp As UDPSocket        'zmienna jako UDPSocket
    Dim MyLan As ServerSocket    'do komunikacji TCP (tutaj inne wykorzystanie)
    
 End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Dim iplist As List                'zdeklarowanie zmiennej typu LIST (lista IP)
    Dim matip As String                'zmienna przechowująca adres IP
    Dim matport As Int                'zmienna przechowująca adres port
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    
    matip = "192.168.1.17"        'wpisanie ip do zmiennej
    matport = 8899                'wpisanie portu do zmiennej
    
    If FirstTime Then
        MyLan.Initialize( "8899", "lan" )                    'inicjalizacja server socket
        udp.Initialize( "udpsrv", matport, 1024 )    'inicjalizacja UDP    ("udpsrv" - do zdarzenia odbiorczego, "" - bez zdarzenai obiorczego)
        iplist.Initialize                            'inicjalizacja listy
    End If
    
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then    'jeśli aplikacja zminimalizowana to
        Activity.Finish        'zakończ aplikację
        ExitApplication        'wyłącz aplikację
    End If
End Sub


Sub Button1_Click
    'Dim index As Int = iplist.IndexOf(GetBroadcastAddress)
    'If index = -1 Then iplist.Add(GetBroadcastAddress)
    'If index >= 0 Then iplist.RemoveAt(index)
    
    Dim address As String = GetBroadcastAddress
    xui.MsgboxAsync(address, "TEST")
    
End Sub



'Returns the UDP broadcast address.
'Returns an empty string if not available.
Sub GetBroadcastAddress As String
    Dim niIterator As JavaObject
    niIterator = niIterator.InitializeStatic("java.net.NetworkInterface").RunMethod("getNetworkInterfaces", Null)
    Do While niIterator.RunMethod("hasMoreElements", Null)
        Dim ni As JavaObject = niIterator.RunMethod("nextElement", Null)
        If ni.RunMethod("isLoopback", Null) = False Then
            Dim addresses As List = ni.RunMethod("getInterfaceAddresses", Null)
            For Each ia As JavaObject In addresses
                Dim broadcast As Object = ia.RunMethod("getBroadcast", Null)
                If broadcast <> Null Then
                    Dim b As String = broadcast
                    Return b.SubString(1)
                End If
            Next
        End If
    Loop
    Return ""
End Sub
 
Top