简体   繁体   English

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

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

I'm using Android Studio 1.3 Today I'm giving a manual IP address in a string. 我正在使用Android Studio 1.3。今天,我在字符串中提供一个手动IP地址。

On my laptop I'm running a web server. 在我的笔记本电脑上,我正在运行Web服务器。 On my Android Studio I'm running a client. 在我的Android Studio上,我正在运行一个客户端。 The problem is that I'm currently connecting to the web server manually using the hard-coded IP address. 问题是我当前正在使用硬编码的IP地址手动连接到Web服务器。

I have a router in my PC room and I connect to the router network with my laptop. 我在PC机房中有一个路由器,并用笔记本电脑连接到路由器网络。 For example, my laptop IP address is 10.0.0.3 and if I log in to my router settings I can see the laptop connected. 例如,我的笔记本电脑IP地址是10.0.0.3,如果我登录到路由器设置,则可以看到笔记本电脑已连接。

The problem is sometimes if my PC shut down for some reason it might be that next time it will be connected to my router with a different IP address. 问题有时是如果我的PC由于某种原因而关闭,则可能是下一次它将以不同的IP地址连接到我的路由器。

In my Java side in the Android Studio I did: 在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();
    }

Then in the addListenerOnButton: 然后在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();
            }
        });
    }
}

Now in my PC room the laptop IP address is 10.0.0.3 I also added my laptop to my router as a static IP address with the laptop mac. 现在在我的PC机房中,笔记本电脑的IP地址是10.0.0.3。我还将笔记本电脑作为笔记本电脑mac的静态IP地址添加到路由器。

In my Java code I have a string with 10.0.0.3, but if I take my laptop and my Android device to my living room there there is a different network the laptop's IP address will be something else. 在我的Java代码中,我有一个带10.0.0.3的字符串,但是如果我将笔记本电脑和Android设备带到客厅,则存在另一个网络,则笔记本电脑的IP地址将是其他名称。

What I want to do is that when I click the button now it's only trying to connect to the given IP address in the string but I want that it will detect automatic the laptop IP address in the router and will connect to it. 我想做的是,当我现在单击按钮时,它仅尝试连接到字符串中的给定IP地址,但我希望它会自动检测路由器中的笔记本电脑IP地址并将其连接。

So I will not need to change in my java code all the time the IP address in the string. 因此,我不需要一直在字符串中更改IP地址。

I think it's called something like umdp not sure. 我认为它不确定umdp之类的东西。

One option you have is to query the Android device's ARP cache. 您拥有的一种选择是查询Android设备的ARP缓存。 Unfortunately, since this is only a list of all the devices that your Android has seen it may not be 100% complete. 不幸的是,由于这只是您的Android设备所见的所有设备的列表,因此可能并非100%完整。 So, what you could do is get your IP then ping all possible IPs on that subnet, forcing the cache to update. 因此,您可以做的是获取IP,然后ping该子网上的所有可能IP,从而强制更新缓存。 From there, you can search the cache for the MAC address of your laptop and read its IP. 从那里,您可以在缓存中搜索笔记本电脑的MAC地址并读取其IP。 Here's some (untested) code I threw together that should help you get on the right track: 这是我整理的一些(未经测试的)代码,可以帮助您走上正确的路:

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

If you call refreshArp() then getIpFromMac() with the MAC of your laptop you should get its IP, so long as they're on the same network. 如果使用笔记本电脑的MAC调用refreshArp()然后使用getIpFromMac() ,则只要它们位于同一网络上,就应该获取其IP。 Again, I haven't tested this code so it may need some tweaking to get it to work. 同样,我没有测试此代码,因此可能需要一些调整才能使其正常工作。

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

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