• c# 获取客户端ip


            在做wcf时,需要得到客户端的ip。一开始用了几种方法总是不好使。后来在网上找到这个方法可以正确的获得客户端的ip了。

            [OperationContract]

            public static string GetClientIp()

            {

                string result = String.Empty;

                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (result != null && result != String.Empty)

                {

                    //可¨¦能¨¹有®D代䨲理¤¨ª

                    if (result.IndexOf(".") == -1)     //没?有®D“¡ã.”¡À肯?定¡§是º?非¤?IPv4格?式º?

                        result = null;

                    else

                    {

                        if (result.IndexOf(",") != -1)

                        {

                            //有®D“¡ã,”¡À,ê?估¨¤计?多¨¤个?代䨲理¤¨ª。¡ê取¨?第̨²一°?个?不?是º?内¨²网ª?的Ì?IP。¡ê

                            result = result.Replace(" ", "").Replace("'", "");

                            string[] temparyip = result.Split(",;".ToCharArray());

                            for (int i = 0; i < temparyip.Length; i++)

                            {

                                if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")

                                {

                                    return temparyip[i];    

                                }

                            }

                        }

                        else if (IsIPAddress(result))

                            return result;

                        else

                            result = null;    

                    }

                }

                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (null == result || result == String.Empty)

                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)

                    result = HttpContext.Current.Request.UserHostAddress;

                return result;

            }

  • 相关阅读:
    hibernate框架的搭建与简单实现增删改
    $.ajax();详解
    利用json实现数据传输
    利用ajax实现数据传输
    错误:Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp;的解决
    简单使用jstl实现敏感字替换
    实用jstl实现未登录时不能绕过登录界面的效果
    简单实用jstl实现“登录|注册”
    简单实用jstl实现代码编写
    简单使用EL进行标签的替换
  • 原文地址:https://www.cnblogs.com/honghong75042/p/3012527.html
Copyright © 2020-2023  润新知