简体   繁体   中英

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.

On my laptop I'm running a web server. On my Android Studio I'm running a client. The problem is that I'm currently connecting to the web server manually using the hard-coded IP address.

I have a router in my PC room and I connect to the router network with my laptop. 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.

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.

In my Java side in the Android Studio I did:

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:

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.

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.

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.

So I will not need to change in my java code all the time the IP address in the string.

I think it's called something like umdp not sure.

One option you have is to query the Android device's ARP cache. Unfortunately, since this is only a list of all the devices that your Android has seen it may not be 100% complete. So, what you could do is get your IP then ping all possible IPs on that subnet, forcing the cache to update. From there, you can search the cache for the MAC address of your laptop and read its 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. Again, I haven't tested this code so it may need some tweaking to get it to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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