什么是我的互联网访问IP

我的电脑上安装了两张局域网卡。 一个用于互联网连接,另一个用于与客户端机器共享互联网。 我用这段代码得到了我的IP:

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

我怎样才能找到哪一个我的互联网连接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 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(); // 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  GetInternetIPAddress(string internetHostName) { // get remote IPs IPHostEntry remoteMachineHostEntry = Dns.GetHostEntry(internetHostName); var internetIPs = new HashSet(); // 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 internetIP = GetInternetIPAddressUsingSocket("google.com", 80); foreach (IPAddress ip in internetIP) { Console.WriteLine(ip); } Console.WriteLine("======"); HashSet internetIP2 = GetInternetIPAddress("google.com"); foreach (IPAddress ip in internetIP2) { Console.WriteLine(ip); } Console.WriteLine("Press any key"); Console.ReadKey(true); } } } 

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

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

路由到Internet的NIC具有网关。 这种方法的好处是您不必进行DNS查找或退回Web服务器。

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

 ///  /// This utility function displays all the IP addresses that likely route to the Internet. ///  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()); } 

您可以使用http://www.whatismyip.org/来回复您的IP。