代码之家  ›  专栏  ›  技术社区  ›  Barun

什么是我的互联网接入IP

  •  4
  • Barun  · 技术社区  · 15 年前

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

    我如何找到哪一个我的互联网连接IP(我不想做的文字处理)?

    4 回复  |  直到 15 年前
        1
  •  3
  •   Andrey    15 年前

    好 啊。我写了两个方法。

    它尝试使用每个本地IP连接到远程主机。

    代码是草稿,所以仔细检查一下。

    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);
            }
        }
    }
    
        2
  •  4
  •   Rob    15 年前

    获取此信息的最佳方法是使用WMI,此程序输出为网络目标“0.0.0.0”注册的网络适配器的IP地址,无论出于何种目的,“不是我的网络”,即“internet”(注意:我不是网络专家,因此可能不完全正确)。

    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);
                    }
    
                }
            }
        }
    }
    
        3
  •  2
  •   Stephen Cleary    15 年前

    路由到Internet的NIC有一个网关。这种方法的好处是,您不必进行DNS查找或跳出web服务器。

    /// <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());
    }
    
        4
  •  1
  •   Hans Passant    15 年前