Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is my internet accessing IP

Tags:

c#

.net

dns

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)?

like image 474
Barun Avatar asked Dec 29 '22 07:12

Barun


2 Answers

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);
                }

            }
        }
    }
}
like image 87
Rob Avatar answered Jan 06 '23 03:01

Rob


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);
        }
    }
}
like image 31
Andrey Avatar answered Jan 06 '23 02:01

Andrey