IpHelper.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. using System.Text;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using System;
  6. using System.ServiceModel;
  7. using System.ServiceModel.Channels;
  8. namespace CommonTool
  9. {
  10. public class IpHelper
  11. {
  12. public static IpHelper Instance { get; } = new IpHelper();
  13. /// <summary>
  14. /// 获取客户端Ip
  15. /// </summary>
  16. /// <returns></returns>
  17. public String GetClientIp()
  18. {
  19. String clientIp = "";
  20. if (System.Web.HttpContext.Current != null)
  21. {
  22. clientIp = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
  23. if (string.IsNullOrEmpty(clientIp) || (clientIp.ToLower() == "unknown"))
  24. {
  25. clientIp = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];
  26. if (string.IsNullOrEmpty(clientIp))
  27. {
  28. clientIp = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
  29. }
  30. }
  31. else
  32. {
  33. clientIp = clientIp.Split(',')[0];
  34. }
  35. }
  36. return clientIp;
  37. }
  38. /// <summary>
  39. /// 服务器端获取客户端请求IP和客户端机器名称
  40. /// </summary>
  41. public void GetClientInfo()
  42. {
  43. OperationContext context = OperationContext.Current;
  44. MessageProperties messageProperties = context.IncomingMessageProperties;
  45. RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
  46. HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
  47. if (endpointProperty != null)
  48. {
  49. string clientIp = !string.IsNullOrEmpty(requestProperty?.Headers["X-Real-IP"]) ? requestProperty.Headers["X-Real-IP"] : endpointProperty.Address;
  50. string clientName = Environment.MachineName;
  51. Console.WriteLine("ClientIp: " + clientIp + "clientName:" + clientName);
  52. }
  53. }
  54. }
  55. #region 根据IP地址获取城市名称
  56. public class IpLocation
  57. {
  58. public string Ip { get; set; }
  59. public string Country { get; set; }
  60. public string Local { get; set; }
  61. }
  62. public class QqWryLocator
  63. {
  64. static readonly Encoding Encoding = Encoding.GetEncoding("GB2312");
  65. private readonly byte[] _data;
  66. readonly int _firstStartIpOffset;
  67. readonly int _ipCount;
  68. public int Count => _ipCount;
  69. public QqWryLocator(string dataPath)
  70. {
  71. dataPath = dataPath ?? FileFuns.GetFullPathFileName("qqwry.dat");
  72. using (FileStream fs = new FileStream(dataPath, FileMode.Open, FileAccess.Read, FileShare.Read))
  73. {
  74. _data = new byte[fs.Length];
  75. fs.Read(_data, 0, _data.Length);
  76. }
  77. _firstStartIpOffset = _data[0] + (_data[1] << 8) + ((_data[2]) << 16) + ((_data[3]) << 24);
  78. var lastStartIpOffset = _data[4] + ((_data[5]) << 8) + ((_data[6]) << 16) + ((_data[7]) << 24);
  79. _ipCount = (lastStartIpOffset - _firstStartIpOffset) / 7 + 1;
  80. if (_ipCount <= 1)
  81. {
  82. throw new ArgumentException("ip FileDataError");
  83. }
  84. }
  85. public static uint IpToInt(string ip)
  86. {
  87. //string[] strArray = ip.Split('.');
  88. //return (uint.Parse(strArray[0]) << 24) + (uint.Parse(strArray[1]) << 16) + (uint.Parse(strArray[2]) << 8) + uint.Parse(strArray[0]);
  89. //return (uint)IPAddress.HostToNetworkOrder((int)(IPAddress.Parse(ip).Address));
  90. byte[] bytes = IPAddress.Parse(ip).GetAddressBytes();
  91. return bytes[3] + (((uint)bytes[2]) << 8) + (((uint)bytes[1]) << 16) + (((uint)bytes[0]) << 24);
  92. }
  93. public static string IntToIp(uint ipInt)
  94. {
  95. return new IPAddress(ipInt).ToString();
  96. }
  97. public IpLocation Query(string ip)
  98. {
  99. IPAddress address = IPAddress.Parse(ip);
  100. if (address.AddressFamily != AddressFamily.InterNetwork)
  101. {
  102. throw new ArgumentException("不支持非IPV4的地址");
  103. }
  104. if (IPAddress.IsLoopback(address))
  105. {
  106. return new IpLocation() { Ip = ip, Country = "本机内部环回地址", Local = string.Empty };
  107. }
  108. uint intIp = (uint)IPAddress.HostToNetworkOrder((int)address.Address);
  109. //if ((((intIP >= IpToInt("0.0.0.0")) && (intIP <= IpToInt("2.255.255.255"))) || ((intIP >= IpToInt("64.0.0.0")) && (intIP <= IpToInt("126.255.255.255")))) ||
  110. //((intIP >= IpToInt("58.0.0.0")) && (intIP <= IpToInt("60.255.255.255"))))
  111. //if (intIP <= 50331647 || (intIP >= 1073741824 && intIP <= 2130706431) || (intIP >= 973078528 && intIP <= 1023410175))
  112. //{
  113. // return new IPLocation() { IP = ip, Country = "网络保留地址", Local = string.Empty };
  114. //}
  115. IpLocation ipLocation = new IpLocation() { Ip = ip };
  116. uint right = (uint)_ipCount;
  117. uint left = 0;
  118. uint startIp;
  119. uint endIpOff;
  120. int countryFlag;
  121. while (left < (right - 1))
  122. {
  123. var middle = (right + left) / 2;
  124. startIp = GetStartIp(middle, out endIpOff);
  125. if (intIp == startIp)
  126. {
  127. left = middle;
  128. break;
  129. }
  130. if (intIp <= startIp)
  131. right = middle;
  132. else
  133. left = middle;
  134. }
  135. startIp = GetStartIp(left, out endIpOff);
  136. var endIp = GetEndIp(endIpOff, out countryFlag);
  137. if ((startIp <= intIp) && (endIp >= intIp))
  138. {
  139. string local;
  140. ipLocation.Country = GetCountry(endIpOff, countryFlag, out local);
  141. ipLocation.Local = local;
  142. }
  143. else
  144. {
  145. ipLocation.Country = "未知";
  146. ipLocation.Local = string.Empty;
  147. }
  148. return ipLocation;
  149. }
  150. private uint GetStartIp(uint left, out uint endIpOff)
  151. {
  152. int leftOffset = (int)(_firstStartIpOffset + (left * 7));
  153. endIpOff = _data[4 + leftOffset] + (((uint)_data[5 + leftOffset]) << 8) + (((uint)_data[6 + leftOffset]) << 16);
  154. return _data[leftOffset] + (((uint)_data[1 + leftOffset]) << 8) + (((uint)_data[2 + leftOffset]) << 16) + (((uint)_data[3 + leftOffset]) << 24);
  155. }
  156. private uint GetEndIp(uint endIpOff, out int countryFlag)
  157. {
  158. countryFlag = _data[4 + endIpOff];
  159. return _data[endIpOff] + (((uint)_data[1 + endIpOff]) << 8) + (((uint)_data[2 + endIpOff]) << 16) + (((uint)_data[3 + endIpOff]) << 24);
  160. }
  161. /// <summary>
  162. /// Gets the country.
  163. /// </summary>
  164. /// <param name="endIpOff">The end ip off.</param>
  165. /// <param name="countryFlag">The country flag.</param>
  166. /// <param name="local">The local.</param>
  167. /// <returns>country</returns>
  168. private string GetCountry(uint endIpOff, int countryFlag, out string local)
  169. {
  170. string country;
  171. uint offset = endIpOff + 4;
  172. switch (countryFlag)
  173. {
  174. case 1:
  175. case 2:
  176. country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
  177. offset = endIpOff + 8;
  178. local = (1 == countryFlag) ? string.Empty : GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
  179. break;
  180. default:
  181. country = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
  182. local = GetFlagStr(ref offset, ref countryFlag, ref endIpOff);
  183. break;
  184. }
  185. return country;
  186. }
  187. private string GetFlagStr(ref uint offset, ref int countryFlag, ref uint endIpOff)
  188. {
  189. while (true)
  190. {
  191. int flag = _data[offset];
  192. //没有重定向
  193. if (flag != 1 && flag != 2)
  194. {
  195. break;
  196. }
  197. if (flag == 2)
  198. {
  199. countryFlag = 2;
  200. endIpOff = offset - 4;
  201. }
  202. offset = _data[1 + offset] + (((uint)_data[2 + offset]) << 8) + (((uint)_data[3 + offset]) << 16);
  203. }
  204. if (offset < 12)
  205. {
  206. return string.Empty;
  207. }
  208. return GetStr(ref offset);
  209. }
  210. /// <summary>
  211. /// 读取字符串...
  212. /// </summary>
  213. /// <param name="offset"></param>
  214. /// <returns></returns>
  215. private string GetStr(ref uint offset)
  216. {
  217. StringBuilder stringBuilder = new StringBuilder(16);
  218. while (true)
  219. {
  220. var lowByte = _data[offset++];
  221. if (lowByte == 0)
  222. {
  223. return stringBuilder.ToString();
  224. }
  225. if (lowByte > 0x7f)
  226. {
  227. var highByte = _data[offset++];
  228. if (highByte == 0)
  229. {
  230. return stringBuilder.ToString();
  231. }
  232. stringBuilder.Append(Encoding.GetString(new[] { lowByte, highByte }));
  233. }
  234. else
  235. {
  236. stringBuilder.Append((char)lowByte);
  237. }
  238. }
  239. }
  240. }
  241. #endregion
  242. }