zoukankan      html  css  js  c++  java
  • 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;

            }

  • 相关阅读:
    less本地环境输出hello-world
    HTML中的SEO和HTML语义化
    JS连等赋值的坑
    React官网首页demo(单文件实现版)
    高并发高可用的架构实践-静态架构蓝图(二)
    高并发高可用的架构实践-设计理念(一)
    云计算+区块链=BaaS
    001/Nginx高可用模式下的负载均衡与动静分离(笔记)
    001---mysql分库分表
    004--PowerDesigner设置显示1对多等关系
  • 原文地址:https://www.cnblogs.com/honghong75042/p/3012527.html
Copyright © 2011-2022 走看看