0

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 ?

  • _"how can i transfer this ip address string to my android device?"_ -- the same way you'd transfer any other data. I'm afraid the question is too broad at best, unclear at worst. You have to follow the same rules any other network server/client scenario would. Auto-discovery usually uses UDP broadcasts, so maybe your Android client can send a UDP broadcast and the server can reply to it (which will automatically provide the server's IP address to the client). – Peter Duniho Nov 27 '15 at 20:14
  • Please distill your question down to a good [mcve] showing clearly what you've tried, with a precise explanation of what that code does and how it's different from what you want it to do. – Peter Duniho Nov 27 '15 at 20:14
  • Peter i never tried using UDP. But how my client can send anything to the web server if i don't have yet the pc ip ? I need the pc ip to connect to it. And what i tried so far is the addListenerOnButton() method that i'm using to loop over the ip's in the array and then to connect to the web server. I will try to change my question to be more minimal and complete. – Sharondohp Sharonas Nov 27 '15 at 20:41
  • _"how my client can send anything to the web server if i don't have yet the pc ip?"_ -- if you'd done a web search on "udp broadcast", you'd know the answer to that question. That's the point of a broadcast: the datagram is delivered to all listeners on the network; as long as the server is listening, it will received the broadcast. The client does not need to know the server's IP address. – Peter Duniho Nov 27 '15 at 21:32
  • You will want to use broadcasting. Here's a link on SO where the OP demonstrates a client and server with UDP broadcasting: http://stackoverflow.com/questions/10832770/sending-udp-broadcast-receiving-multiple-messages. You could have your server just broadcast its IP every few seconds. I'd have to work out the equivalent Java code, but it should not be difficult to find an example. You might run into problems when spanning subnets. – Lorek Nov 27 '15 at 23:17
  • Lorek The example in the link i tried it on the c# and it's working fine. I will try to find now a client code for the java. The server on the c# should broadcast every few seconds the ip of the pc and the client on the java side once it's getting the pc ip i will use the ip right ? And once the client get the ip should i stop the server ? – Sharondohp Sharonas Nov 27 '15 at 23:32

0 Answers0