繁体   English   中英

如何自动找到网络IP地址并连接到它?

[英]How can I find the network IP address automatic and connect to it?

我正在使用Android Studio 1.3。今天,我在字符串中提供一个手动IP地址。

在我的笔记本电脑上,我正在运行Web服务器。 在我的Android Studio上,我正在运行一个客户端。 问题是我当前正在使用硬编码的IP地址手动连接到Web服务器。

我在PC机房中有一个路由器,并用笔记本电脑连接到路由器网络。 例如,我的笔记本电脑IP地址是10.0.0.3,如果我登录到路由器设置,则可以看到笔记本电脑已连接。

问题有时是如果我的PC由于某种原因而关闭,则可能是下一次它将以不同的IP地址连接到我的路由器。

在Android Studio的Java方面,我做到了:

package com.test.webservertest;

public class MainActivity extends ActionBarActivity
{
    private static final int MY_DATA_CHECK_CODE = 0;
    public static MainActivity currentActivity;
    TextToSpeech mTts;
    private String targetURL;
    private String urlParameters;
    private Button btnClick;
    private String clicking = "clicked";
    private String[] ipaddresses = new String[]{
        "http://10.0.0.3:8098/?cmd=nothing"};
    private String iptouse = "";
    private TextView text;
    private boolean connectedtoipsuccess = false;
    private int counter = 0;
    private NotificationCompat.Builder mbuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addListenerOnButton();
        currentActivity = this;
        initTTS();
    }

然后在addListenerOnButton中:

public void addListenerOnButton()
{

btnClick = (Button) findViewById(R.id.checkipbutton);

        btnClick.setOnClickListener(new OnClickListener()
        {
            byte[] response = null;
            @Override
            public void onClick(View arg0)
            {

                text = (TextView) findViewById(R.id.textView2);

                Thread t = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        for (int i = 0; i < ipaddresses.length; i++)

                        {
                                counter = i;
                                try
                                {
                                    response = Get(ipaddresses[i]);
                                }
                                catch (Exception e)
                                {
                                    String err = e.toString();
                                }

                                if (response!=null)
                                {


                                    try
                                    {
                                        final String a = new String(response, "UTF-8");



                                        text.post(new Runnable()
                                        {
                                            @Override
                                            public void run()
                                            {
                                                text.setText(a + " Oמ " + ipaddresses[counter]);

                                                String successconnected = null;
                                                successconnected = "Successfully connected";
                                                textforthespeacch = successconnected;
                                                MainActivity.currentActivity.initTTS();
                                            }
                                        });
                                        iptouse = ipaddresses[i].substring(0,ipaddresses[i].lastIndexOf("=")+1);
                                        connectedtoipsuccess = true;
                                        Logger.getLogger("MainActivity(inside thread)").info(a);
                                    } catch (UnsupportedEncodingException e)
                                    {
                                        e.printStackTrace();
                                        Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
                                    }

                                    Logger.getLogger("MainActivity(inside thread)").info("test1");
                                    break;
                                }
                                else
                                {

                                }

                        }
                        counter = 0;
                        if (response == null)
                        {
                            text.post(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    text.setText("Connection Failed");
                                    String successconnected = null;
                                    successconnected = "connection failed";
                                    textforthespeacch = successconnected;
                                    MainActivity.currentActivity.initTTS();
                                }
                            });
                        }
                    }
                });
                t.start();
            }
        });
    }
}

现在在我的PC机房中,笔记本电脑的IP地址是10.0.0.3。我还将笔记本电脑作为笔记本电脑mac的静态IP地址添加到路由器。

在我的Java代码中,我有一个带10.0.0.3的字符串,但是如果我将笔记本电脑和Android设备带到客厅,则存在另一个网络,则笔记本电脑的IP地址将是其他名称。

我想做的是,当我现在单击按钮时,它仅尝试连接到字符串中的给定IP地址,但我希望它会自动检测路由器中的笔记本电脑IP地址并将其连接。

因此,我不需要一直在字符串中更改IP地址。

我认为它不确定umdp之类的东西。

您拥有的一种选择是查询Android设备的ARP缓存。 不幸的是,由于这只是您的Android设备所见的所有设备的列表,因此可能并非100%完整。 因此,您可以做的是获取IP,然后ping该子网上的所有可能IP,从而强制更新缓存。 从那里,您可以在缓存中搜索笔记本电脑的MAC地址并读取其IP。 这是我整理的一些(未经测试的)代码,可以帮助您走上正确的路:

private static void refereshArp(Context ctx){
    //IP aquisition from http://stackoverflow.com/a/6071963/1896516
    WifiManager wm = (WifiManager) ctx.getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
    String[] parts = ip.split(".");
    String subnet = parts[0] + "." + parts[1] + "." + parts[2] + ".";
    Runtime rt = Runtime.getRuntime();
    for(int i=0; i<256; i++){
        try{
            rt.exec("ping -c1 " + subnet + i)
        }catch(IOException e){
            continue;
        }
    }

}

//Adapted from http://www.flattermann.net/2011/02/android-howto-find-the-hardware-mac-address-of-a-remote-host/
private static String getIpFromMac(String mac) {
    if (mac == null)
        return null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");
            if (splitted != null && splitted.length >= 4 && mac.equals(splitted[3])) {
                // return the ip of the device
                return splitted[0];
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

如果使用笔记本电脑的MAC调用refreshArp()然后使用getIpFromMac() ,则只要它们位于同一网络上,就应该获取其IP。 同样,我没有测试此代码,因此可能需要一些调整才能使其正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM