使用c#查找我正在使用的电脑的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地址字符串传输到我的Android设备?
我需要这样做的原因是在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();
}
}
}
在我的android设备上使用android studio我做了一个连接到pc web服务器的客户端。今天我正在做的是自己查找pc ip地址并将其分配给android studio。
在MainActivity中:
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.5:8098/?cmd=nothing"};
然后按一下按钮监听方法,点击Listener:
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();
}
});
}
所以这就是它今天的工作方式: 我去了我的客厅,在那里我添加到我的路由器我的电脑静态IP。 然后我去了我的电脑室,我有另一个网络与另一个网络,我也添加了PC静态IP。
然后将两个ip添加到android studio代码然后我循环遍历数组以查看连接的那个,然后我知道这是正确的ip使用。
问题是我不能要求用户将路由器分配给静态IP,然后用数组填充android工作室......
我需要做的是以某种方式将pc ip自动分配到android studio(到我的android设备),这样它就可以使用它了。 所以我知道使用c#来查找我的电脑ip,但我如何将它传递给Android设备并使用它呢?
我可以扫描在android工作室上扫描一下将扫描所有ips从0到255,然后尝试识别那个是PC但这可能需要很长时间。
另一种选择可能是使用c#通过gmail发送在我的电脑上找到的ip i,并从gmail的android studio中获取它并将其添加到数组中?这是逻辑吗?