0

I am working on a P2P Chat Application using TcpClient and sockets.

I have written the following code to accept tcpclient:

IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());
IPAddress ip_local = Dns.GetHostAddresses(Dns.GetHostName())[0];
// IPAddress ip_local = IPAddress.Parse(ip_local);
TcpListener tcpl = new TcpListener(new IPEndPoint(ip_local, 9277));
while (true)
{
    try
    {
        tcpl.Start();
        TcpClient tcpClient = tcpl.AcceptTcpClient();
        StateObject state = new StateObject();
        state.workSocket = tcpClient.Client;
        tcpClient.Client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(OnReceive), state);
    }
    catch (Exception ex)
    {

    }
}

The problem is that it picks different network [as I have 1 LAN and 2 VMWARE networks] every time. So the question is how to force it to take the network address of LAN, i.e. a particular network?

Jeff B
  • 8,572
  • 17
  • 61
  • 140
Akshita
  • 849
  • 8
  • 15

3 Answers3

0

You are grabbing the local IP address from the DNS hostname. The problem is likely one or both (but in sequence) are registering their addresses as your host name automatically. You have a couple options: 1) change DNS host name to point to the correct address; 2) grab the address specifically, the function GetHostAddresses takes an IP address as parameter or host name.

inevio
  • 837
  • 6
  • 12
0

Look at this answer which recommends against using Dns.GetHostAddresses and provides a more thorough approach.

Not sure, but I think the System.Net.NetworkInformation.IPInterfaceProperties may be of interest here.

Community
  • 1
  • 1
Kevin P. Rice
  • 5,550
  • 4
  • 33
  • 39
0

So this is all about how to detect the correct localIP to pass too the TcpListener constructor as you seem to be doing already:

TcpListener tcpl = new TcpListener(new IPEndPoint(ip_local, 9277));

This was a particularly non trivial problem we solved in the open source network framework, networkComms.net. If you have a look at the Getter for LocalIP on line 80 here, there are a couple ways of doing it:

  1. Ping a known external IP and then use the network adaptor that was chosen by the OS (using iphlpapi.dll, so windows supported only).
  2. Searching through all known IP adaptors using NetworkInterface.GetAllNetworkInterfaces() and selecting one where an IP matches a provided prefix, such as 192.* etc.

The basic 11 example of how to use networkComms.net might also be of interest, here.

MarcF
  • 3,169
  • 2
  • 30
  • 57