Java 获取我的设备的 WiFi Direct IP 地址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20263726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:40:49  来源:igfitidea点击:

Getting WiFi Direct IP address of my device

javaandroidipwifi-direct

提问by Talib

I am trying to get the ip address of my device but all in vain and no success. I've tried

我正在尝试获取我设备的 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;
    }

but its giving me 0.0.0.0 and no other method is working too..Help !!

但它给了我 0.0.0.0 并且没有其他方法也有效..帮助!

采纳答案by kapil thadani

send out the peer's local ip address (starting with 192.168.x.x) to the group owner. After this "handshake", which doesn't really take time, it's all good to go. Did not find any other way to get the peer's ip addresses, the only information provided by GroupListener/PeerListener/... is the mac address.

向组所有者发送对等方的本地 IP 地址(以 192.168.xx 开头)。在这次“握手”之后,这并不需要时间,一切都很好。没有找到其他方法获取peer的ip地址,GroupListener/PeerListener/...提供的唯一信息就是mac地址。

回答by mico

Do you have permissions on the WiFi settings attached to your Android program manifest? At least ACCESS_WIFI_STATEis needed [1]. If that is not enough, probably ACCESS_NETWORK_STATEis also needed [2]. I did not find anything bad on your code, so trying to play with Manifest would be my suggestion.

您对附加到您的 Android 程序清单的 WiFi 设置有权限吗?至少ACCESS_WIFI_STATE需要[1]。如果这还不够,可能ACCESS_NETWORK_STATE还需要[2]。我没有发现你的代码有任何不好的地方,所以我的建议是尝试使用 Manifest。

The first link I have as source has in the accepted answer also INTERNETpermission, so that your program can also contact somewhere to ask for connection and thus IP. That would be the next permission to try, if the two first don't work.

我作为来源的第一个链接在接受的答案中也有INTERNET权限,这样你的程序也可以联系某个地方来请求连接,从而请求 IP。如果两个第一个不起作用,那将是下一个尝试的许可。

You asked about official or credible sources, these are from the credible ones. Every peace of information is voted up on Stackoverflow at least once, and that if something says that these stuff have made it at least for someone.

您询问了官方或可信来源,这些来自可信来源。Stackoverflow 上的每一个和平信息都至少被投票一次,如果有人说这些东西至少对某人来说是成功的。

My sources:

我的消息来源:

[1] How to get IP address of the device from code?

[1]如何从代码中获取设备的IP地址?

[2] Android WifiManager getConnectionInfo requires CHANGE_WIFI_STATE?

[2] Android WifiManager getConnectionInfo 需要 CHANGE_WIFI_STATE?

回答by Budius

Just as reference: I'm the developer of the WiFi-Shoot (a direct file transfer app via WiFi Direct).

仅供参考:我是WiFi-Shoot(通过 WiFi Direct 的直接文件传输应用程序)的开发人员

Unfortunately, there's no way to get your own IP address, and the general principle of operation is slightly different:

不幸的是,没有办法获得自己的IP地址,一般操作原理略有不同:

  • All the operations will be made with the WiFiP2PManager
  • call initializeto get a Channel, all other operations needs this channel.
  • after you discoverPeersand connectto one of them
  • you can requestGroupInfothat will tell you if that device is the group owner and what is the group owner IP address. So non-owners can connect to the owner using the supplied address and the owner will listen to connections.
  • you can also requestPeersthat will give you a list of all connected peers. That includes MAC addresses and names.
  • 所有操作都将通过WiFiP2PManager 进行
  • 调用initialize获取一个通道,所有其他操作都需要这个通道。
  • 在你discoverPeersconnect其中一个之后
  • 您可以requestGroupInfo告诉您该设备是否是组所有者以及组所有者 IP 地址是什么。因此,非所有者可以使用提供的地址连接到所有者,所有者将侦听连接。
  • 你也可以requestPeers这样会给你一个所有连接对等点的列表。这包括 MAC 地址和名称。

The call Context.getSystemService(Context.WIFI_P2P_SERVICE)will give you a WiFiP2PManager.

调用Context.getSystemService(Context.WIFI_P2P_SERVICE)会给你一个 WiFiP2PManager。

And yes, you'll need a bunch of WiFI permission such as ACCESS_WIFI_STATE, CHANGE_WIFI_STATEamong others.

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

回答by AndroidHacker

If you are trying to get IP address of other device connected to WiFi network

如果您正在尝试获取连接到 WiFi 网络的其他设备的 IP 地址

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

        System.out.println(Address);

Getting Internet IP address i.e live IP 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();
        }

For more deeper knowledge and other native methods fallow link

有关更深入的知识和其他本地方法的休耕链接

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

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

回答by souvickcse

Use this code

使用此代码

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

And add the permission to your manifest.

并将权限添加到您的清单中。

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

回答by pinxue

Firstly, check manifest file for permissions:

首先,检查清单文件的权限:

<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"/>

Then, define what's IP looking for. If you want to broadcast that IP for purpose beyond the service discovering, find it by using WIFI_SERVICE. If you are curious about the ip address of your service broadcasting, NsdServiceInfo instance has getHost() method.

然后,定义要查找的 IP。如果您想广播该 IP 用于服务发现之外的目的,请使用 WIFI_SERVICE 找到它。如果您对服务广播的 IP 地址感到好奇,NsdServiceInfo 实例具有 getHost() 方法。

回答by Dipendra

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; }
         */
    }