tags:

views:

131

answers:

4

I have two lan cards installed in my pc. One is for internet connection and another for share the internet to client machines. I am getting my IP with this code:

IPHostEntry HosyEntry = Dns.GetHostEntry((Dns.GetHostName()));
foreach (IPAddress ip in HosyEntry.AddressList)
{
    trackingIp = ip.ToString();
    textBox1.Text += trackingIp + ",";
}

How can I find which one my internet connecting IP (I dont want to do it by text processing)?

+1  A: 

You could use http://www.whatismyip.org/ it echos back your IP.

Hans Passant
Well I want to track my machine ip. By your process It will get back me virtual ip if I dont have a static ip. I need core machine lan ip.
Barun
Are you talking about 127.0.0.1 (localhost)? Always your own machine, no need to get the real address.
Hans Passant
@Hans Passant: From what I understand he want to know which NIC is used for internet access. IOW what routes to the outside world.
leppie
no My lan ip is 172.16.203.51 But whatismyip returning me 115.111.40.70
Barun
Use System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces().
Hans Passant
@babaidebnath: You don't *have* a "core machine lan ip", you have multiple IP's. If you want to know which one you're using when you connect to the internet, then connect to the internet and look at what IP the client side of your socket is bound to. You don't even need that web site; anything that accepts a connection will do.
Steven Sudit
@Hans Passant: Can you give idea how it will work ?
Barun
@Steven Sudit: I am not connecting with any client.
Barun
@babaidebnath: Then you'll never be sure. :-)
Steven Sudit
+4  A: 

The best way to get this information is to use WMI, this program outputs the IP addresses for the network adapter that's registered for the network destination "0.0.0.0", which is for all intents and purposes "not my network", aka "the internet" (Note: I'm not a networking expert so that may not be entirely correct).

using System;
using System.Management;

namespace ConsoleApplication10
{
    class Program
    {
        static void Main(string[] args)
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", 
                "SELECT * FROM Win32_IP4RouteTable WHERE Destination=\"0.0.0.0\"");

            int interfaceIndex = -1;

            foreach (var item in searcher.Get())
            {
                interfaceIndex = Convert.ToInt32(item["InterfaceIndex"]);
            }

            searcher = new ManagementObjectSearcher("root\\CIMV2",
                string.Format("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE InterfaceIndex={0}", interfaceIndex));

            foreach (var item in searcher.Get())
            {
                var ipAddresses = (string[])item["IPAddress"];

                foreach (var ipAddress in ipAddresses)
                {
                    Console.WriteLine(ipAddress);
                }

            }
        }
    }
}
Rob
Thanks for reply. Now I will try your code.
Barun
Ok it showing an exception InvalidQuery
Barun
+2  A: 

Ok. I wrote 2 methods.

First method is faster but require to use a socket. It tries to connect to remote host using each local IP.

Second methos is slower and did not use sockets. It connects to remote host (get response, waste some traffic) and look for local IP in the active connections table.

Code is draft so double check it.

namespace ConsoleApplication1
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;

    class Program
    {
        public static List<IPAddress> GetInternetIPAddressUsingSocket(string internetHostName, int port)
        {
            // get remote host  IP. Will throw SocketExeption on invalid hosts
            IPHostEntry remoteHostEntry = Dns.GetHostEntry(internetHostName);
            IPEndPoint remoteEndpoint = new IPEndPoint(remoteHostEntry.AddressList[0], port);

            // Get all locals IP
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

            var internetIPs = new List<IPAddress>();
            // try to connect using each IP             
            foreach (IPAddress ip in hostEntry.AddressList) {
                IPEndPoint localEndpoint = new IPEndPoint(ip, 80);

                bool endpointIsOK = true;
                try {
                    using (Socket socket = new Socket(localEndpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) {
                        socket.Connect(remoteEndpoint);
                    }
                }
                catch (Exception) {
                    endpointIsOK = false;
                }

                if (endpointIsOK) {
                    internetIPs.Add(ip); // or you can return first IP that was found as single result.
                }
            }

            return internetIPs;
        }

        public static HashSet <IPAddress> GetInternetIPAddress(string internetHostName)
        {
            // get remote IPs
            IPHostEntry remoteMachineHostEntry = Dns.GetHostEntry(internetHostName);

            var internetIPs = new HashSet<IPAddress>();

            // connect and search for local IP
            WebRequest request = HttpWebRequest.Create("http://" + internetHostName);
            using (WebResponse response = request.GetResponse()) {
                IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
                TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
                response.Close();

                foreach (TcpConnectionInformation t in connections) {
                    if (t.State != TcpState.Established) {
                        continue;
                    }

                    bool isEndpointFound = false;
                    foreach (IPAddress ip in remoteMachineHostEntry.AddressList) {
                        if (ip.Equals(t.RemoteEndPoint.Address)) {
                            isEndpointFound = true;
                            break;
                        }
                    }

                    if (isEndpointFound) {
                        internetIPs.Add(t.LocalEndPoint.Address);
                    }
                }
            }

            return internetIPs;
        }


        static void Main(string[] args)
        {

            List<IPAddress> internetIP = GetInternetIPAddressUsingSocket("google.com", 80);
            foreach (IPAddress ip in internetIP) {
                Console.WriteLine(ip);
            }

            Console.WriteLine("======");

            HashSet<IPAddress> internetIP2 = GetInternetIPAddress("google.com");
            foreach (IPAddress ip in internetIP2) {
                Console.WriteLine(ip);
            }

            Console.WriteLine("Press any key");
            Console.ReadKey(true);
        }
    }
}
Andrey
Great. Thanks for Reply.
Barun
+2  A: 

NICs that route to the Internet have a gateway. The benefit of this approach is that you don't have to do a DNS lookup or bounce of a web server.

Here's some code that displays local IPs for a NIC that has a valid gateway:

/// <summary> 
/// This utility function displays all the IP addresses that likely route to the Internet. 
/// </summary> 
public static void DisplayInternetIPAddresses()
{
    var sb = new StringBuilder();

    // Get a list of all network interfaces (usually one per network card, dialup, and VPN connection) 
    var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

    foreach (var network in networkInterfaces)
    {
        // Read the IP configuration for each network 
        var properties = network.GetIPProperties();

        // Only consider those with valid gateways
        var gateways = properties.GatewayAddresses.Select(x => x.Address).Where(
            x => !x.Equals(IPAddress.Any) && !x.Equals(IPAddress.None) && !x.Equals(IPAddress.Loopback) &&
            !x.Equals(IPAddress.IPv6Any) && !x.Equals(IPAddress.IPv6None) && !x.Equals(IPAddress.IPv6Loopback));
        if (gateways.Count() < 1)
            continue;

        // Each network interface may have multiple IP addresses 
        foreach (var address in properties.UnicastAddresses)
        {
            // Comment these next two lines to show IPv6 addresses too
            if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                continue;

            sb.AppendLine(address.Address + " (" + network.Name + ")");
        }
    }

    MessageBox.Show(sb.ToString());
}
Stephen Cleary