C#获取网络IP,获取ip地址

1 网络请求接口时,获取ip
01.

[HttpPost]
[Route("Login")]
public HttpResponseMessage UserLogin()
 {
 ReturnResult result = new ReturnResult() { code = "", msg = "" };
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象

string ip=getIP();
}

02.获取ip的方法

public string  getIP()
{
string ip="":
//先获取网络请求的ip
string textip=HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

         foreach (var hostAddress in Dns.GetHostAddresses(textip))
            {
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                  ip=  hostAddress.ToString();
            }


//如果网络ip为空,则获取局域网ip
  if(ip	=="")	
  {
           foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
                    ip=hostAddress.ToString();
            }

  }
return ip;
}

你可能感兴趣的:(C#基础,缓存,c#,redis)