c# - 获取本地IP地址

标签 c# networking

在 Internet 上有几个地方向您展示了如何获取 IP 地址。其中很多看起来像这个例子:

String strHostName = string.Empty;
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;

for (int i = 0; i < addr.Length; i++)
{
    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();

在这个例子中,我获得了多个 IP 地址,但我只对获得路由器分配给运行该程序的计算机的 IP 地址感兴趣:如果某人希望访问共享文件夹,我将提供的 IP 地址例如我的电脑。

如果我没有连接到网络,而是通过没有路由器的调制解调器直接连接到互联网,那么我想得到一个错误。我如何查看我的计算机是否已通过 C# 连接到网络,如果是,则获取 LAN IP 地址。

最佳答案

获取本地IP地址:

public static string GetLocalIPAddress()
{
    var host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            return ip.ToString();
        }
    }
    throw new Exception("No network adapters with an IPv4 address in the system!");
}

检查您是否已连接:

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

关于c# - 获取本地IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803073/

相关文章:

c# - 是否可以通过 Silverlight 应用程序操作远程(在服务器上)xml/txt 数据库文件?

C# 使用附加参数附加事件处理

python - 当您连接到 2 个网络时,如何使用 scapy 通过特定接口(interface)发送数据包?

python - python twisted framework HttpClient是否访问代理?

c# - WCF 与 WCF 双工与套接字

c# - 此请求的授权已被拒绝 - 新的 Web API 项目

c# - 为 json.net 编写可重用的 JsonConverter

c# - List<T> 在类中使用

networking - 连接到专用网络上的服务器

linux - Iptables:将端口从一台主机转发到同一桥接网络内的另一台主机