To find the ip address of the pc i'm using with c# In the constructor:
localipadd = GetLocalIPAddress();
And the GetLocalIPAdress method:
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!");
}
For example i'm getting the ip 10.0.01 Now the problem is how can i transfer this ip address string to my android device ?
The reason i need to do it is that on the c# i'm running a web server: In the constructor:
var ws = new WebServer(
request => Task.Run(() => SendResponseAsync(request)),
"http://+:8098/");
ws.Run();
And the WebServer class:
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();
}
}
}
And on my android device using android studio i did a client that connect to the pc web server. Today what i'm doing is finding on my own the pc ip address and assign it to the android studio.
In the MainActivity:
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.5:8098/?cmd=nothing"};
And then a button listen method with button click 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();
}
});
}
So this is how it work today: I went to my living room and there i added to my router my pc static ip. Then i went to my pc room i have another router with another network and i added there the pc static ip too.
And then added both ip's to the android studio code and then i'm looping over the array to see the one that connected and then i know this is the right ip to use.
The problem is that i can't ask the user/s to assign to the router a static ip and then fill the android studio with the array.....
What i need to do is somehow to assign the pc ip automatic to the android studio(to my android device) so it will be able to use it. So i know using the c# to find my pc ip but how do i pass it to the android device and use it ?
I could scan make a scan on the android studio something that will scan all the ips from 0 to 255 and then to try to identify the one that is the pc but this might take a very long time.
Another option maybe could be sending the ip i found on my pc using the c# via gmail and get it with the android studio from the gmail and add it to the array ? Is that logic ?