有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在我的无线网络上找到我的pc本地ip地址并将ip传送到我的安卓设备?

查找我与c一起使用的pc的ip地址# 在构造函数中:

localipadd = GetLocalIPAddress();

还有GetLocalIPAdress方法:

public static string GetLocalIPAddress()
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("Local IP Address Not Found!");
        }

例如,我得到了ip 10.0.01 现在的问题是如何将这个ip地址字符串传输到我的安卓设备

我需要这样做的原因是,在c#上,我正在运行一个web服务器: 在构造函数中:

var ws = new WebServer(
    request => Task.Run(() => SendResponseAsync(request)),
    "http://+:8098/");
ws.Run();

以及WebServer类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;

namespace Automatic_Record
{
    class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, Task<string>> _responderMethod;

        public WebServer(string[] prefixes, Func<HttpListenerRequest, Task<string>> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");

            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");

            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);

            _responderMethod = method;
            _listener.Start();
        }

        public WebServer(Func<HttpListenerRequest, Task<string>> method, params string[] prefixes)
            : this(prefixes, method) { }

        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("Webserver running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem(async (c) =>
                        {
                            var ctx = c as HttpListenerContext;
                            try
                            {
                                string rstr = await _responderMethod(ctx.Request);
                                System.Diagnostics.Trace.Write(ctx.Request.QueryString);
                                //ctx.Request.QueryString

                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                                System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();

                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }

        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }
}

在我使用安卓 studio的安卓设备上,我做了一个连接到pc网络服务器的客户端。今天我要做的是自己找到pc的ip地址,并将其分配给安卓 studio

在主要活动中:

private String[] ipaddresses = new String[]{
            "http://10.0.0.1:8098/?cmd=nothing",
            "http://192.168.1.5:8098/?cmd=nothing"}; 

然后是一个带有按钮点击监听器的按钮监听方法:

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 + " On \n" + ipaddresses[counter]);
                                            status1.setText("Connected");
                                            String successconnected = null;
                                            successconnected = "Successfully connected";
                                            textforthespeacch = successconnected;
                                            MainActivity.this.initTTS();
                                        }
                                    });
                                    iptouse = ipaddresses[i].substring(0, ipaddresses[i].lastIndexOf("=") + 1);
                                    connectedtoipsuccess = true;
                                    connectedSuccess = 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");
                                    status1.setText("Connection Failed");
                                    String successconnected = null;
                                    successconnected = "connection failed";
                                    textforthespeacch = successconnected;
                                    MainActivity.this.initTTS();
                                }
                            });
                        }
                    }
                });
                t.start();
            }
        });

    }

这就是它今天的工作原理: 我去了我的客厅,在那里我把我的pc静态ip添加到我的路由器上。 然后我去了我的电脑室,我有另一个路由器和另一个网络,我在那里添加了电脑静态ip

然后将两个ip都添加到安卓 studio代码中,然后我在阵列上循环查看连接的ip,然后我知道这是正确的ip

问题是,我不能要求用户为路由器分配一个静态ip,然后用数组填充安卓 studio

我需要做的是以某种方式将pc ip自动分配给安卓 studio(我的安卓设备),以便它能够使用它。 所以我知道使用c#查找我的pc ip,但我如何将其传递到安卓设备并使用它

我可以在安卓 studio上进行扫描,扫描范围从0到255的所有IP,然后尝试识别pc,但这可能需要很长时间

另一个选择可能是通过gmail发送我在pc上使用c#找到的ip,然后通过安卓 studio从gmail获取并添加到阵列中?这是逻辑吗


共 (0) 个答案