C# 如何获取服务器IP地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1345676/
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 server IP Address?
提问by JL.
Is there a 1 line method to get the IP Address of the server?
是否有 1 行方法来获取服务器的 IP 地址?
Thanks
谢谢
采纳答案by Zhaph - Ben Duguid
Request.ServerVariables["LOCAL_ADDR"];
From the docs:
从文档:
Returns the server address on which the request came in. This is important on computers where there can be multiple IP addresses bound to the computer, and you want to find out which address the request used.
返回请求进入的服务器地址。这对于可能有多个 IP 地址绑定到计算机的计算机很重要,并且您想找出请求使用的地址。
This is distinct from the Remote addresses which relate to the client machine.
这与与客户端机器相关的远程地址不同。
回答by Faizan S.
From searching the net I found following code: (I couldn't find a single line method there)
通过搜索网络,我发现了以下代码:(我在那里找不到单行方法)
string myHost = System.Net.Dns.GetHostName();
// Show the hostname
MessageBox.Show(myHost);
// Get the IP from the host name
string myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[index].ToString();
// Show the IP
MessageBox.Show(myIP);
-> where indexis the index of your ip address host (ie. network connection).
-> 其中index是您的 IP 地址主机的索引(即网络连接)。
Code from: http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
代码来自:http: //www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html
回答by Mark Carpenter
As other(s) have posted, System.Net.Dns.GetHostEntry
is the way to go. When you access the AddressList
property, you'll want to take the AddressFamily
property into account, as it could return both IPv4 AND IPv6 results.
正如其他人发布的那样,System.Net.Dns.GetHostEntry
是要走的路。当您访问该AddressList
属性时,您需要考虑该AddressFamily
属性,因为它可能会返回 IPv4 和 IPv6 结果。
回答by TAHA SULTAN TEMURI
This method will return your machine public IP address when run this code on your PC and when you deploy your application on server will return Server IP address.
在您的 PC 上运行此代码时,此方法将返回您的机器公共 IP 地址,当您在服务器上部署应用程序时,将返回服务器 IP 地址。
public static string Getpublicip()
{
try
{
string externalIP = "";
var request = (HttpWebRequest)WebRequest.Create("http://icanhazip.com.ipaddress.com/");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
externalIP = new WebClient().DownloadString("http://icanhazip.com");
return externalIP;
}
catch (Exception e)
{
return "null";
}
}