如何获取运行我的 C# 应用程序的服务器的 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1069103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the IP address of the server on which my C# application is running on?
提问by Nefzen
I am running a server, and I want to display my own IP address.
我正在运行一个服务器,我想显示我自己的 IP 地址。
What is the syntax for getting the computer's own (if possible, external) IP address?
获取计算机自己(如果可能,外部)IP 地址的语法是什么?
Someone wrote the following code.
有人写了下面的代码。
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
However, I generally distrust the author, and I don't understand this code. Is there a better way to do so?
但是,我一般不信任作者,我不理解这段代码。有没有更好的方法来做到这一点?
回答by Andrew Hare
Nope, that is pretty much the best way to do it. As a machine couldhave several IP addresses you need to iterate the collection of them to find the proper one.
不,这几乎是最好的方法。由于一台机器可能有多个 IP 地址,因此您需要迭代它们的集合以找到合适的 IP 地址。
Edit:The only thing I wouldchange would be to change this:
编辑:我唯一要改变的就是改变这个:
if (ip.AddressFamily.ToString() == "InterNetwork")
to this:
对此:
if (ip.AddressFamily == AddressFamily.InterNetwork)
There is no need to ToString
an enumeration for comparison.
不需要ToString
枚举进行比较。
回答by mfloryan
namespace NKUtilities
{
using System;
using System.Net;
using System.Net.Sockets;
public class DNSUtility
{
public static int Main(string [] args)
{
string strHostName = "";
try {
if(args.Length == 0)
{
// 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);
}
else
{
// Otherwise, get the IP address of the host provided on the command line.
strHostName = args[0];
}
// 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());
}
return 0;
}
catch(SocketException se)
{
Console.WriteLine("{0} ({1})", se.Message, strHostName);
return -1;
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}.", ex.Message);
return -1;
}
}
}
}
Look herefor details.
详情请看这里。
You have to remember your computer can have more than one IP (actually it always does) - so which one are you after.
您必须记住,您的计算机可以拥有多个 IP(实际上它总是如此) - 那么您在追求哪一个。
回答by opedog
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
Just tested this on my machine and it works.
刚刚在我的机器上测试了这个,它可以工作。
回答by Juan Calero
Maybe by externalIP you can consider (if you are in a Web server context) using this
也许通过外部IP,您可以考虑(如果您在 Web 服务器上下文中)使用此
Request.ServerVariables["LOCAL_ADDR"];
I was asking the same question as you and I found it in thisstackoverflow article.
我和你问了同样的问题,我在这篇stackoverflow 文章中找到了它。
It worked for me.
它对我有用。
回答by ezgar
The only way to know your public IP is to ask someone else to tell you; this code may help you:
知道你的公共 IP 的唯一方法是让别人告诉你;此代码可以帮助您:
public string GetPublicIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
return direction;
}
回答by James
WebClient webClient = new WebClient();
string IP = webClient.DownloadString("http://myip.ozymo.com/");
回答by The Mask
Try this:
尝试这个:
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
String MyIp = localIPs[0].ToString();
回答by Mohammed A. Fadil
Cleaner and an all in one solution :D
清洁剂和多合一解决方案:D
//This returns the first IP4 address or null
return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
回答by detect the public IP address
For getting the current public IP address, all you need to do is create an ASPX page with the following line on the page load event:
要获取当前的公共 IP 地址,您需要做的就是在页面加载事件中使用以下行创建一个 ASPX 页面:
Response.Write(HttpContext.Current.Request.UserHostAddress.ToString());
回答by Dr. Wily's Apprentice
If you can't rely on getting your IP address from a DNS server (which has happened to me), you can use the following approach:
如果您不能依赖从 DNS 服务器获取 IP 地址(这发生在我身上),您可以使用以下方法:
The System.Net.NetworkInformation namespace contains a NetworkInterface class, which has a static GetAllNetworkInterfaces method.
System.Net.NetworkInformation 命名空间包含一个NetworkInterface 类,该类具有静态GetAllNetworkInterfaces 方法。
This method will return all "network interfaces" on your machine, and there are generally quite a few, even if you only have a wireless adapter and/or an ethernet adapter hardware installed on your machine. All of these network interfaces have valid IP addresses for your local machine, although you probably only want one.
这种方法将返回您机器上的所有“网络接口”,通常有很多,即使您的机器上只安装了无线适配器和/或以太网适配器硬件。所有这些网络接口都具有本地计算机的有效 IP 地址,尽管您可能只需要一个。
If you're looking for one IP address, then you'll need to filter the list down until you can identify the right address. You will probably need to do some experimentation, but I had success with the following approach:
如果您正在寻找一个 IP 地址,那么您需要向下过滤列表,直到您可以确定正确的地址。您可能需要进行一些实验,但我使用以下方法取得了成功:
- Filter out any NetworkInterfaces that are inactive by checking for
OperationalStatus == OperationalStatus.Up
. This will exclude your physical ethernet adapter, for instance, if you don't have a network cable plugged in.
- 通过检查
OperationalStatus == OperationalStatus.Up
. 这将排除您的物理以太网适配器,例如,如果您没有插入网络电缆。
For each NetworkInterface, you can get an IPInterfacePropertiesobject using the GetIPProperties method, and from an IPInterfaceProperties object you can access the UnicastAddresses propertyfor a list of UnicastIPAddressInformationobjects.
对于每个 NetworkInterface,您可以使用GetIPProperties 方法获取IPInterfaceProperties对象,并且您可以从 IPInterfaceProperties 对象访问UnicastAddresses 属性以获取UnicastIPAddressInformation对象列表。
- Filter out non-preferred unicast addresses by checking for
DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
- Filter out "virtual" addresses by checking for
AddressPreferredLifetime != UInt32.MaxValue
.
- 通过检查过滤掉非首选单播地址
DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred
- 通过检查
AddressPreferredLifetime != UInt32.MaxValue
.
At this point I take the address of the first (if any) unicast address that matches all of these filters.
在这一点上,我获取与所有这些过滤器匹配的第一个(如果有)单播地址的地址。
EDIT:
编辑:
[revised code on May 16, 2018 to include the conditions mentioned in the text above for duplicate address detection state and preferred lifetime]
[2018 年 5 月 16 日修订代码以包含上述文本中提到的重复地址检测状态和首选生命周期的条件]
The sample below demonstrates filtering based on operational status, address family, excluding the loopback address (127.0.0.1), duplicate address detection state, and preferred lifetime.
下面的示例演示了基于操作状态、地址族、不包括环回地址 (127.0.0.1)、重复地址检测状态和首选生命周期的过滤。
static IEnumerable<IPAddress> GetLocalIpAddresses()
{
// Get the list of network interfaces for the local computer.
var adapters = NetworkInterface.GetAllNetworkInterfaces();
// Return the list of local IPv4 addresses excluding the local
// host, disconnected, and virtual addresses.
return (from adapter in adapters
let properties = adapter.GetIPProperties()
from address in properties.UnicastAddresses
where adapter.OperationalStatus == OperationalStatus.Up &&
address.Address.AddressFamily == AddressFamily.InterNetwork &&
!address.Equals(IPAddress.Loopback) &&
address.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred &&
address.AddressPreferredLifetime != UInt32.MaxValue
select address.Address);
}