32 lines
1.0 KiB
C#
32 lines
1.0 KiB
C#
using System.Net;
|
||
using Microsoft.AspNetCore.Http;
|
||
using Microsoft.IdentityModel.Tokens;
|
||
|
||
namespace Bunny.Common.Utils.Net;
|
||
|
||
public static partial class NetUtil
|
||
{
|
||
/// <summary>
|
||
/// 获取请求的IP地址
|
||
/// </summary>
|
||
/// <param name="context">HttpContext 上下问对象</param>
|
||
/// <param name="getIpv4AddressType">是否获取IPv4地址,默认为IPv4</param>
|
||
/// <returns>IP地址</returns>
|
||
public static string GetRequestIpAddress(HttpContext context, bool getIpv4AddressType = true)
|
||
{
|
||
// 获取IP地址
|
||
var ipAddress = context.Connection.RemoteIpAddress!.ToString();
|
||
// 转换IP地址格式
|
||
var ip = IPAddress.Parse(ipAddress);
|
||
// 转换成IPv4
|
||
var toIPv4 = ip.MapToIPv4().ToString();
|
||
// 转换成IPv6
|
||
var toIPv6 = ip.MapToIPv6().ToString();
|
||
|
||
// 如果获取IPv4地址
|
||
ipAddress = getIpv4AddressType ? toIPv4 : toIPv6;
|
||
|
||
// 如果有IP直接返回
|
||
return ipAddress.IsNullOrEmpty() ? "" : ipAddress;
|
||
}
|
||
} |