C#获取IP及判断IP是否在区间的示例代码


本文摘自PHP中文网,作者黄舟,侵删。

本文主要介绍了C# 获取IP及判断IP是否在区间的方法。具有很好的参考价值,下面跟着小编一起来看下吧

话不多说,请看代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

/// <summary>

  /// 获取客户端IP

  /// </summary>

  /// <returns></returns>

  public static string GetClientIpAddress()

    {

      var httpContext = HttpContext.Current;

      if (httpContext.Request.ServerVariables == null)

      {

        return null;

      }

      var clientIp = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ??             

      httpContext.Request.ServerVariables["REMOTE_ADDR"];

      try

      {

        foreach (var hostAddress in Dns.GetHostAddresses(clientIp))

        {

          if (hostAddress.AddressFamily == AddressFamily.InterNetwork)

          {

            return hostAddress.ToString();

          }

        }

        foreach (var hostAddress in Dns.GetHostAddresses(Dns.GetHostName()))

        {

          if (hostAddress.AddressFamily == AddressFamily.InterNetwork)

          {

            return hostAddress.ToString();

          }

        }

      }

      catch (Exception ex)

      {

 

      }

      return clientIp;

    }

  /// <summary>

  /// ip是否在ip空间内

  /// </summary>

  /// <param name="ip"></param>

  /// <param name="ipSection"></param>

  /// <returns></returns>

  public static Boolean ipExistsInRange(String ip, String ipSection)

  {

    ipSection = ipSection.Trim();

    ip = ip.Trim();

    int idx = ipSection.IndexOf('-');

    String beginIP = ipSection.Substring(0, idx);

    String endIP = ipSection.Substring(idx + 1);

    return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);

 

  }

  public static long getIp2long(String ip)

  {

    ip = ip.Trim();

    String[] ips = ip.Split('.');

    long ip2long = 0L;

    for (int i = 0; i < 4; ++i)

    {

      ip2long = ip2long << 8 | Int64.Parse(ips[i]);

    }

    return ip2long;

  }

  public static long getIp2long2(String ip)

  {

    ip = ip.Trim();

    String[] ips = ip.Split('.');

    long ip1 = Int64.Parse(ips[0]);

    long ip2 = Int64.Parse(ips[1]);

    long ip3 = Int64.Parse(ips[2]);

    long ip4 = Int64.Parse(ips[3]);

    long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4;

    return ip2long;

  }

以上就是C#获取IP及判断IP是否在区间的示例代码的详细内容!

相关阅读 >>

C#开发 winform如何在选项卡中集成加载多个窗体 实现窗体复用详解(图)

C#开发实例-订制屏幕截图工具(十)在截图中包含鼠标指针形状

C#实现base64处理的加密解密,编码解码的示例代码

C# gridcontrol的模糊查询实现代码实例

详解C#winform打开excel文档的方法总结

C#向word文档插入和隐藏段落的方法介绍

使用C#生成pdf文件流的代码案例分享

简单介绍C#中list<t>对象的深度拷贝问题

C#如何使用 oledbconnection 连接读取excel?(代码实例)

C#和c ++的区别是什么

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...