开发者

How to obtain Local IP?

I read this question in this thread: How to get the IP address of the server on which my C# application is running on?

But this code is not worki开发者_JAVA技巧ng for me:

string hostname = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(hostname);

It giving me an err on this second line in the argument:

A field initializer cannot reference the non-static field, method, or property.

I want to store my local IP of my machine in a string. Thats all!


public static String GetIP()
{
    String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

   if(string.IsNullOrEmpty(ip))
    {
        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }

    return ip;
}


//This will return the collection of local IP's
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

public static bool IsLocalIpAddress(string host)
{
  try
  { // get host IP addresses
    IPAddress[] hostIPs = Dns.GetHostAddresses(host);
    // get local IP addresses
    IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

    // test if any host IP equals to any local IP or to localhost
    foreach (IPAddress hostIP in hostIPs)
    {
      // is localhost
      if (IPAddress.IsLoopback(hostIP)) return true;
      // is local address
      foreach (IPAddress localIP in localIPs)
      {
        if (hostIP.Equals(localIP)) return true;
      }
    }
  }
  catch { }
  return false;
}
//Call this method this will tell Is this your local Ip
IsLocalIpAddress("localhost");


In ASP.Net, you can get the IP address to which the request was made from the Request object:

string myIpAddress = Request.UserHostAddress ;

It may be an IPv4 address or an IPv6 address. To find out, parse it into an System.Net.IPAddress:

IPAddress addr = IPAddress.Parse( myIpAddress ) ;

If you're interested in the IP address of the current host, that turns into a much more complicated (interesting?) question.

Any given host (and for "host" read "individual computer") may have multiple NICs (Network Interface Card) installed. Each NIC (assuming it's attached to an IP network) has an IP address assigned to it—and likely it has both an IPv4 and an IPv6 address assigned to it.

Further, each NIC may itself be multi-homed and have additional IP addresses, either IPv4 and/or IPv6 assigned.

Then we have the IP loopback adapter, for which each host shares the same loopback addresses. For IPv4, the loopback address is defined as the entire 127/8 subnet (that is, IP addresses 127.0.0.0–127.255.255.255 are all IPv4 loopback addresses). IPv6 only assigns a single loopback address (::1).

So, from the vantage point of the host then, you need to know the context (loopback adapter or NIC? if NIC, which one? Ipv4 or IPv6?) And even then, you're not guaranteed a single IP address. You have to ask yourself what, exactly, it is you mean by "my IP address"?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜