如何获得用于访问Internet网络适配器的IP地址 [英] How to get IP address of network adapter used to access the internet

查看:118
本文介绍了如何获得用于访问Internet网络适配器的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有发现我机的网络适配器,它被用来访问互联网(因为这是一个我想结合我的服务器)的IPv4地址的可靠方法。我曾经获得的本地IP地址这样的名单:

  ip地址IP = System.Net.Dns.GetHostByName(Environment.MachineName).AddressList [0];
 

和它工作得很好,但今天,它失败了,因为我一直在寻找的IP地址是不是第一个在这个地址列表,但第三个一(因为我有2个虚拟机运行,这两个创建的虚拟适配器)。

任何意见将是多少AP preciated。

解决方案

  ip地址IP = System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList.Where(I => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault();
 

作为一种替代方式,你可以使用:

 使用System.Net.NetworkInformation;

// ...

VAR本地= NetworkInterface.GetAllNetworkInterfaces()式(I => i.Name ==本地连接)。FirstOrDefault()。
变种stringAddress = local.GetIPProperties()UnicastAddresses [0] .Address.ToString()。
VAR ip地址= IPAddress.Parse(stringAddress);
 

在这里你只需要更换的 本地连接 的与你的控制适配器的名称面板\网络和Internet \网络连接

I'm wondering if there's a reliable way of finding the IPv4 address of the network adapter in my machine which is used to access the internet (since this is the one I'd like to bind my server to). I used to get a list of local ip addresses like this:

IPAddress ip = System.Net.Dns.GetHostByName(Environment.MachineName).AddressList[0];

And it worked fine but today it failed because the IP address I was looking for was not the first one in this address list but the 3rd one (since I had 2 virtual machines running and both of these created a virtual adapter).

Any advice would be much appreciated.

解决方案

IPAddress ip = System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList.Where(i => i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).FirstOrDefault();

As an alternative way, you could use:

using System.Net.NetworkInformation;

//...

var local = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == "Local Area Connection").FirstOrDefault();
var stringAddress = local.GetIPProperties().UnicastAddresses[0].Address.ToString();
var ipAddress = IPAddress.Parse(stringAddress);

where you just have to replace the "Local Area Connection" with the name of your adapter in the Control Panel\Network and Internet\Network Connections

这篇关于如何获得用于访问Internet网络适配器的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆