Skip to content

Commit

Permalink
兼容IPV6
Browse files Browse the repository at this point in the history
  • Loading branch information
MonoLogueChi committed Aug 7, 2019
1 parent 7765fa7 commit 341f083
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 32 deletions.
5 changes: 3 additions & 2 deletions Danmaku/Model/DanmakuModel.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.Numerics;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

Expand All @@ -9,7 +10,7 @@ public class DanmakuModel : DanmakuGet
{
[MaxLength(32)] public string Id { get; set; }

public long Ip { get; set; }
public BigInteger Ip { get; set; }
public string Referer { get; set; }
public DateTime Date { get; set; } = DateTime.Now;
}
Expand Down Expand Up @@ -48,7 +49,7 @@ public DanmakuInsert(DanmakuModel danmaku)

public object[] Data { get; set; }

public long Ip { get; set; }
public BigInteger Ip { get; set; }
public string Referer { get; set; }
public long Date { get; set; }

Expand Down
61 changes: 31 additions & 30 deletions Danmaku/Utils/Ip.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,39 @@
using System.Text;
// Copyright @ 2019 矿冶园
// Product: 实验室安全手机版
// Subsystem: Danmaku
// Author: 迟竞雷
// Time: 2019-07-24 8:54
// Description:

using System.Net;
using System.Numerics;

namespace Danmaku.Utils
{
public class Ip
{
/// <summary>
/// Ip转化为10进制
/// </summary>
/// <param name="ip">点分隔的ip</param>
/// <returns>十进制ip</returns>
public static long Ip2Long(string ip)
{
if (string.IsNullOrWhiteSpace(ip)) return 0;
char[] separator = {'.'};
var items = ip.Split(separator);
return (long.Parse(items[0]) << 24)
| (long.Parse(items[1]) << 16)
| (long.Parse(items[2]) << 8)
| long.Parse(items[3]);
}

/// <summary>
/// 十进制ip转换为字符串
/// </summary>
/// <param name="ipInt">十进制ip</param>
/// <returns>字符串ip</returns>
public static string Long2Ip(long ipInt)
{
/// <summary>
/// Ip转化为10进制
/// </summary>
/// <param name="ip">点分隔的ip</param>
/// <returns>十进制ip</returns>
public static BigInteger Ip2Long(string ip)
{
if (string.IsNullOrWhiteSpace(ip)) return 0;
if (IPAddress.TryParse(ip, out var a))
return new BigInteger(a.GetAddressBytes());
return 0;
}

/// <summary>
/// 十进制ip转换为字符串
/// </summary>
/// <param name="ipInt">十进制ip</param>
/// <returns>字符串ip</returns>
public static string Long2Ip(BigInteger ipInt)
{
var sb = new StringBuilder();
sb.Append((ipInt >> 24) & 0xFF).Append(".");
sb.Append((ipInt >> 16) & 0xFF).Append(".");
sb.Append((ipInt >> 8) & 0xFF).Append(".");
sb.Append(ipInt & 0xFF);
return sb.ToString();
var a = ipInt.ToByteArray();
return new IPAddress(a).ToString();
}
}
}

0 comments on commit 341f083

Please sign in to comment.