簡體   English   中英

獲取我的設備的WiFi直接IP地址

[英]Getting WiFi Direct IP address of my device

我試圖獲取我的設備的IP地址,但都是徒勞的,沒有成功。 我試過了

public String getP2PIpAddr() {
       WifiManager wifiManager = (WifiManager) getSystemService(WIFI_P2P_SERVICE);
       WifiInfo wifiInfo = wifiManager.getConnectionInfo();
       int ip = wifiInfo.getIpAddress();

       String ipString = String.format(
       "%d.%d.%d.%d",
       (ip & 0xff),
       (ip >> 8 & 0xff),
       (ip >> 16 & 0xff),
       (ip >> 24 & 0xff));

       return ipString;
    }

但它給我0.0.0.0,沒有其他方法也工作..幫助!!

就像參考:我是WiFi-Shoot(通過WiFi Direct的直接文件傳輸應用程序)的開發者

不幸的是,沒有辦法獲得自己的IP地址,操作的一般原則略有不同:

  • 所有操作都將使用WiFiP2PManager進行
  • 調用initialize以獲取Channel,所有其他操作都需要此通道。
  • 在您discoverPeersconnect到其中一個之后
  • 您可以requestGroupInfo ,它將告訴您該設備是否是組所有者以及組所有者IP地址是什么。 因此,非所有者可以使用提供的地址連接到所有者,所有者將收聽連接。
  • 您還可以requestPeers為您提供所有已連接對requestPeers列表的用戶。 這包括MAC地址和名稱。

調用Context.getSystemService(Context.WIFI_P2P_SERVICE)將為您提供WiFiP2PManager。

是的,您需要一堆WiFI權限,例如ACCESS_WIFI_STATECHANGE_WIFI_STATE等。

將對等方的本地IP地址(以192.168.xx開頭)發送給組所有者。 在這次“握手”之后,這並不需要時間,這一切都很好。 沒有找到任何其他方式來獲取對等方的IP地址,GroupListener / PeerListener / ...提供的唯一信息是mac地址。

public static String getIpAddress() {
    try {
        List<NetworkInterface> interfaces = Collections
                .list(NetworkInterface.getNetworkInterfaces());
        /*
         * for (NetworkInterface networkInterface : interfaces) { Log.v(TAG,
         * "interface name " + networkInterface.getName() + "mac = " +
         * getMACAddress(networkInterface.getName())); }
         */

        for (NetworkInterface intf : interfaces) {
            if (!getMACAddress(intf.getName()).equalsIgnoreCase(
                    Globals.thisDeviceAddress)) {
                // Log.v(TAG, "ignore the interface " + intf.getName());
                // continue;
            }
            if (!intf.getName().contains("p2p"))
                continue;

            Log.v(TAG,
                    intf.getName() + "   " + getMACAddress(intf.getName()));

            List<InetAddress> addrs = Collections.list(intf
                    .getInetAddresses());

            for (InetAddress addr : addrs) {
                // Log.v(TAG, "inside");

                if (!addr.isLoopbackAddress()) {
                    // Log.v(TAG, "isnt loopback");
                    String sAddr = addr.getHostAddress().toUpperCase();
                    Log.v(TAG, "ip=" + sAddr);

                    boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);

                    if (isIPv4) {
                        if (sAddr.contains("192.168.49.")) {
                            Log.v(TAG, "ip = " + sAddr);
                            return sAddr;
                        }
                    }

                }

            }
        }

    } catch (Exception ex) {
        Log.v(TAG, "error in parsing");
    } // for now eat exceptions
    Log.v(TAG, "returning empty ip address");
    return "";
}

public static String getMACAddress(String interfaceName) {
        try {
            List<NetworkInterface> interfaces = Collections
                    .list(NetworkInterface.getNetworkInterfaces());

            for (NetworkInterface intf : interfaces) {
                if (interfaceName != null) {
                    if (!intf.getName().equalsIgnoreCase(interfaceName))
                        continue;
                }
                byte[] mac = intf.getHardwareAddress();
                if (mac == null)
                    return "";
                StringBuilder buf = new StringBuilder();
                for (int idx = 0; idx < mac.length; idx++)
                    buf.append(String.format("%02X:", mac[idx]));
                if (buf.length() > 0)
                    buf.deleteCharAt(buf.length() - 1);
                return buf.toString();
            }
        } catch (Exception ex) {
        } // for now eat exceptions
        return "";
        /*
         * try { // this is so Linux hack return
         * loadFileAsString("/sys/class/net/" +interfaceName +
         * "/address").toUpperCase().trim(); } catch (IOException ex) { return
         * null; }
         */
    }

您是否擁有附加到Android程序清單的WiFi設置的權限? 至少需要ACCESS_WIFI_STATE [1] 如果這還不夠,可能還需要ACCESS_NETWORK_STATE [2] 我沒有發現你的代碼有什么不好,所以嘗試使用Manifest將是我的建議。

我作為源的第一個鏈接在接受的答案中也有INTERNET權限,這樣你的程序也可以聯系某處詢問連接,從而知道IP。 如果這兩個首先不起作用,這將是下一次嘗試的許可。

你問過官方或可靠的消息來源,這些來自可信的消息來源。 每一次信息的和平都至少在Stackoverflow上投了一次,而且如果有人說這些東西至少對某人有用了。

我的來源:

[1] 如何從代碼中獲取設備的IP地址?

[2] Android WifiManager getConnectionInfo需要CHANGE_WIFI_STATE?

如果您正在嘗試獲取連接到WiFi網絡的其他設備的IP地址

try {
            Address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        System.out.println(Address);

獲取Internet IP地址即實時IP地址

String myUrl = "http://api.externalip.net/ip";
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(myUrl);

        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity ht = httpResponse.getEntity();
            BufferedHttpEntity buf = new BufferedHttpEntity(ht);
            InputStream is = buf.getContent();
            BufferedReader r = new BufferedReader(new InputStreamReader(is));
            StringBuilder total = new StringBuilder();
            String ipaddress = r.readLine();
            Toast.makeText(getApplicationContext(),"Live IP : " + ipaddress, Toast.LENGTH_LONG).show();
        }catch(Exception e){
            e.printStackTrace();
        }

有關更深層次的知識和其他本地方法的休閑鏈接

http://developer.android.com/guide/topics/connectivity/wifip2p.html

首先,檢查清單文件的權限:

<uses-permission
    android:required="true"
    android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission
    android:required="true"
    android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission
    android:required="true"
    android:name="android.permission.INTERNET"/>

然后,定義要查找的IP。 如果您希望在服務發現之外廣播該IP,請使用WIFI_SERVICE查找。 如果您對服務廣播的IP地址感到好奇,則NsdServiceInfo實例具有getHost()方法。

使用此代碼

WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
String ipAddress = Formatter.formatIpAddress(ip); 

並為您的清單添加權限。

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM