Azuken Posté(e) 5 novembre 2012 Share Posté(e) 5 novembre 2012 Bonjour, Je cherche à créer une application qui mettrais en place un serveur web sur le téléphone. Sur l'exemple que j'ai repris, il fait une récupération de l'adresse ip en Wifi. (l'exemple : https://gist.github.com/1893396) WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); final String formatedIpAddress = String.format("%d.%d.%d.%d", (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff)); Sauf que n'étant pas connecté en wifi, j'obtient 0.0.0.0... J'ai cherché sur le net une fonction qui permettrais de récupérer l'adresse IP quand on est en 3G, mais je n'ai rien trouvé... Auriez vous une solution ? Merci d'avance, Azuken Je viens de trouver la solution, j'ai réupéré d'un tutoriel une fonction. public String getMonAdresseIP() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) return inetAddress.getHostAddress(); } } } catch (SocketException e) { e.printStackTrace(); } return null; } Citer Lien vers le commentaire Partager sur d’autres sites More sharing options...
Bebeuz Posté(e) 28 novembre 2012 Share Posté(e) 28 novembre 2012 Je viens de tomber là dessus par hasard en cherchant la même chose que toi chez moi ta solution ne marche pas, la méthode getMonAdresseIP() renvoie systématiquement null. Voici donc une autre solution : public static String getIP(WifiManager wifiManager) { int myIp = wifiManager.getConnectionInfo().getIpAddress(); int intMyIp3 = myIp / 0x1000000; int intMyIp3mod = myIp % 0x1000000; int intMyIp2 = intMyIp3mod / 0x10000; int intMyIp2mod = intMyIp3mod % 0x10000; int intMyIp1 = intMyIp2mod / 0x100; int intMyIp0 = intMyIp2mod % 0x100; String s = String.valueOf(intMyIp0) + "." + String.valueOf(intMyIp1) + "." + String.valueOf(intMyIp2) + "." + String.valueOf(intMyIp3); boolean chaineOK = true; for (int i = 0; i < s.length(); i++) if(s.charAt(i) != '.' && !Character.isDigit(s.charAt(i))) chaineOK = false; if (!chaineOK) s = null; return s; } Que tu appelle de cette façon dans ton Activity : getIP((WifiManager) getSystemService(WIFI_SERVICE)); Citer Lien vers le commentaire Partager sur d’autres sites More sharing options...
Recommended Posts
Rejoignez la conversation
Vous pouvez poster maintenant et vous enregistrez plus tard. Si vous avez un compte, connectez-vous maintenant pour poster.