2009-08-28 228 views
26

是否有1行方法来获取服务器的IP地址?如何获取服务器IP地址?

感谢

+0

你是什么意思“服务器” - ASP.Net加工机或服务器端防火墙/门/代理 – Dewfy 2009-08-28 08:23:53

+2

你需要考虑到有可能分配给您的服务器多个IP地址。 – UserControl 2009-08-28 08:28:28

+0

http://stackoverflow.com/q/646525/292060可能有重复,尽管这有更好的选择答案。 – goodeye 2014-12-20 04:49:55

回答

54
Request.ServerVariables["LOCAL_ADDR"]; 

docs

返回在其请求进来的服务器地址这是计算机上的重要哪里有可以绑定多个IP地址计算机,并且你想知道请求使用了哪个地址。

这不同于与客户端计算机相关的远程地址。

+0

+1 Nice ,我不知道那是存在的。 – Pwninstein 2009-08-28 08:39:09

+0

是的,很多事情都隐藏在ServerVariables集合中。 – 2009-08-28 09:13:49

+2

完美的答案 - 从旧的ASP经典日子里,我应该记住这一个:) – 2009-08-31 05:09:22

6

从搜索网,我发现下面的代码:(我无法找到有单行法)

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); 

- >其中指数是您的IP地址的索引主机(即网络连接)。

代码来自:http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html

0

当您在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"; 
     } 

    }