获取本地IP地址 [英] Get local IP address

查看:210
本文介绍了获取本地IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在互联网有几个地方,告诉你如何获得一个IP地址。而他们中的很多像这样的例子:

In the internet there are several places that show you how to get an IP address. And a lot of them look like this example:

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我的电脑的实例。

With this example I get several IP addresses, but I'm only interested in getting the one that the router assigns to the computer running the program: the IP that I would give to someone if he wishes to access a shared folder in my computer for instance.

如果我没有连接到网络上,我通过不带路由器的调制解调器,直接连接到互联网,然后我想获得一个错误。我怎么能看看我的计算机连接到与C#的网络,如果是则获得LAN IP地址。

If I am not connected to a network and I am connected to the internet directly via a modem with no router then I would like to get an error. How can I see if my computer is connected to a network with C# and if it is then to get the LAN IP address.

推荐答案

要获取本地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("Local IP Address Not Found!");
    }

要检查您是否连接与否:

To check if you're connected or not:

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

这篇关于获取本地IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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