Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的互联网接入IP是什么_C#_.net_Dns - Fatal编程技术网

C# 我的互联网接入IP是什么

C# 我的互联网接入IP是什么,c#,.net,dns,C#,.net,Dns,我的电脑中安装了两个lan卡。一个用于internet连接,另一个用于与客户端计算机共享internet。我正在使用以下代码获取我的IP: IPHostEntry HosyEntry = Dns.GetHostEntry((Dns.GetHostName())); foreach (IPAddress ip in HosyEntry.AddressList) { trackingIp = ip.ToString(); textBox1.Text += trackingIp + "

我的电脑中安装了两个lan卡。一个用于internet连接,另一个用于与客户端计算机共享internet。我正在使用以下代码获取我的IP:

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

如何找到我的internet连接IP(我不想通过文本处理)中的哪一个?

您可以使用它回显您的IP。

获取此信息的最佳方法是使用WMI,此程序输出为网络目标“0.0.0”注册的网络适配器的IP地址,这就是“不是我的网络”,也就是“互联网”(注:我不是网络专家,所以这可能不完全正确)


嗯。我写了两个方法

第一种方法速度更快,但需要使用套接字。 它尝试使用每个本地IP连接到远程主机

第二种方法比较慢,并且没有使用套接字。它连接到远程主机(获取响应,浪费一些流量),并在活动连接表中查找本地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);
        }
    }
}
命名空间控制台应用程序1
{
使用制度;
使用System.Collections.Generic;
Net系统;
使用System.Net.NetworkInformation;
使用System.Net.Sockets;
班级计划
{
公共静态列表GetInternetIPAddressUsingSocket(字符串internetHostName,int-port)
{
//获取远程主机IP。将在无效主机上抛出SocketExection
IPHostEntry remoteHostEntry=Dns.GetHostEntry(internetHostName);
IPEndPoint remoteEndpoint=新IPEndPoint(remoteHostEntry.AddressList[0],端口);
//获取所有本地IP
IPHostEntry hostEntry=Dns.GetHostEntry(Dns.GetHostName());
var internetIPs=新列表();
//尝试使用每个IP连接
foreach(hostEntry.AddressList中的ip地址ip){
IPEndPoint localEndpoint=新的IPEndPoint(ip,80);
bool endpointIsOK=true;
试一试{
使用(套接字套接字=新套接字(localEndpoint.Address.AddressFamily,SocketType.Stream,ProtocolType.Tcp)){
socket.Connect(远程端点);
}
}
捕获(例外){
endpointIsOK=false;
}
if(endpointIsOK){
internetIPs.Add(ip);//或者您可以返回作为单个结果找到的第一个ip。
}
}
返回互联网;
}
公共静态哈希集GetInternetIPAddress(字符串internetHostName)
{
//获取远程IP
IPHostEntry remoteMachineHostEntry=Dns.GetHostEntry(internetHostName);
var internetIPs=newhashset();
//连接并搜索本地IP
WebRequest=HttpWebRequest.Create(“http://”+internetHostName);
使用(WebResponse=request.GetResponse()){
IPGlobalProperties属性=IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[]connections=properties.GetActiveTcpConnections();
response.Close();
foreach(连接中的TcpConnectionInformation t){
如果(t.State!=TcpState.builded){
继续;
}
bool isEndpointFound=false;
foreach(remoteMachineHostEntry.AddressList中的ip地址ip){
if(ip.Equals(t.RemoteEndPoint.Address)){
isEndpointFound=true;
打破
}
}
如果(isEndpointFound){
Add(t.LocalEndPoint.Address);
}
}
}
返回互联网;
}
静态void Main(字符串[]参数)
{
List internetIP=GetInternetIPAddressUsingSocket(“google.com”,80);
foreach(Internet中的ip地址ip){
控制台写入线(ip);
}
Console.WriteLine(“=======”);
HashSet internetIP2=GetInternetIPAddress(“google.com”);
foreach(internetIP2中的ip地址ip){
控制台写入线(ip);
}
Console.WriteLine(“按任意键”);
Console.ReadKey(true);
}
}
}

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

以下是显示具有有效网关的NIC的本地IP的一些代码:

/// <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());
}
//
///此实用程序功能显示可能路由到Internet的所有IP地址。
///  
公共静态void DisplayInternetIPAddresses()
{
var sb=新的StringBuilder();
//获取所有网络接口的列表(通常每个网卡、拨号和VPN连接一个)
var networkInterfaces=NetworkInterface.GetAllNetworkInterfaces();
foreach(网络接口中的var网络)
{
//读取每个网络的IP配置
var properties=network.GetIPProperties();
/只考虑那些有效网关
var gateways=properties.GatewayAddresses.Select(x=>x.Address)。其中(
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)
继续;
//每个网络接口可能有多个IP地址
foreach(properties.unicastaddress中的var地址)
{
//注释下两行以显示IPv6地址
if(address.address.AddressFamily!=AddressFamily.InterNetwork)
继续;
(某人)
/// <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());
}