Hi,
I have a client application that communicates with other server modules residing on other machines. In client application, I need to know the IP address of the machine it is running on, so that it would communicate its IP to the server module(which could be separated from client by routers).
Retrieving IP is not a problem. But when I retrieve IP, it gives IP of all the adapters present on the machine. How do I know using which IP it would communicate to the server module?

Is there a way to resolve this?...or some functionality wherein I will pass the distination to connect to and it will return me the IP it is using for connection.

Recommended Answers

All 4 Replies

This is how i do it to store the local IPv4 IP address. This module checks for all of the IP addresses on all of the adapters and returns the first IP address that is not a loopback address. Then bind your socket to the LanAddress IPAddress

public IPAddress LanAddress; // bind client socket to this address.
public void GetLocalIP()
{    
    string myHost = System.Net.Dns.GetHostName(); // create a string to store the Dns Host Name
    string MyLocalIP = "";

    System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost); // Store the IPs of the host name.

    // Loop through all IP addresses. 

    foreach (System.Net.IPAddress myIP in myIPs.AddressList)
    {
        if (!myIP.IsIPv6LinkLocal)
        {
            // If not Loop back address store it in MyLocalIP and Store the IPAddress
            if (myIP.ToString() != "127.0.0.1") 
            {
                MyLocalIP = myIP.ToString();
                LanAddress = IPAddress.Parse(myIP.ToString());
                break;
            }
        }
    }
}

Eliminating loopback IP is not what is required.

Suppose I am connected to two networks through two LAN cards on my machine.
Each LAN card is having different IP.
I have address of target machine to connect to.
Now, I need to know which network interface would it be using to communicate to target machine?

Retrieving the IPAddresses for each adapter and placing it into an IPAddress array can give you the IP Address for each adapter.
array[0] being adapter 0.
array[1] being adapter 1.

The previous code stored adapter 0 in a non arrayed variable called LocalIPAddress, however if you changed this to an array value you can store any IPAddress that is not the loopback in this array.

public IPAddress[] LocalIPAddress = new IPAddress[2] // 2 being for the amount of adapters connected.
adapter</param>
public void GetExternalIP()
{

int count = 0; // used to count the adapters.
    string myHost = System.Net.Dns.GetHostName(); // create a string to store the Dns Host Name

    System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost); // Store the IPs of the host name.

    // Loop through all IP addresses and display each 

    foreach (System.Net.IPAddress myIP in myIPs.AddressList)
    {
        if (!myIP.IsIPv6LinkLocal)
        {
            // If not Loop back address store it in MyLocalIP and Store the IPAddress
            if (myIP.ToString() != "127.0.0.1") 
            {
                LocalIPAddress [count] = IPAddress.Parse(myIP.ToString());
                count ++;
                if (count >= 2) // if greater than max adapters
               {
                   break;
               }
            }
        }
    }
}

As you can see all i did was change the LocalIPAddress to an array, and made sure that if the array, is not larger than the amount of adapters to check, then store the IPAddress in the array at the location.

To Check which adapter connects to the server, you can do:

int maxAdapters = 2; // amount of adapters
IPAddress mainAddressToUse;
/// <param name="ipToCheck">IPAddresses to check</param>
/// <param name="adapter">start checking at what adapter</param>
public void CheckAdapters(IPAddress[] ipToCheck, int adapter)
{
    Socket TempSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     // change the 8080 to what port you want to open on client.
    IPEndPoint checkAddress = new IPEndPoint(ipToCheck[adapter], 8080);
    // change the 8080 to open port on server.
    IPEndPoint serverAddress = new IPEndPoint(CentralServerAddress,8080); 
    try
    {                
        TempSocket.BeginConnect(serverAddress, new AsyncCallback(BeginCheck_Async), TempSocket);
        // Wait 100 ms to connect to the Server, if unable to connect throw SocketException
        allDone.WaitOne(100);

        // if connected then store the connected IPAddress as mainAddressToUse.
        mainAddressToUse = ipToCheck[adapter];
    }
    catch (SocketException se)
    {
        adapter++;
        if (adapter < maxAdapters)
        {
            CheckAdapters(ipToCheck, adapter);
        }
        else
        {
            Console.Write("Unable to connect to the Server!");
            // of If using windows forms;
            // MessageBox.Show("Unable to connect to the Server!\n\n" + se.ToString(), "Error - Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

public void BeginCheck_Async(IAsyncResult ar)
{
    Socket workSocket = (Socket)ar.AsyncState;
    workSocket.EndConnect(ar);
    allDone.Reset();
}

This code checks the connection to the server for 100ms if a connection is not made, it checks the next adapter using the IPAddress specified in the array at adapter integer. If it can connect it stores the IPAddress in the mainIPAddressToUse variable.

The mainIPAddressToUse is the IPAddress of the adapter that connects to the server.

I hope this is more of what your looking for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.