C#获取真实IP地址实现方法
作者:shichen2014 发布时间:2022-01-05 11:35:49
本文实例讲述了C#获取真实IP地址实现方法,分享给大家供大家参考。具体实现方法如下:
通常来说,大家获取用户IP地址常用的方法是:
string IpAddress = "";
if((HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]!=null
&& HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] !=String.Empty) )
{
IpAddress=HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ;
}
else
{
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
事实上,上面的代码只试用与用户只使用了1层代理,如果用户有2层,3层HTTP_X_FORWARDED_FOR 的值是:"本机真实IP,1层 * ,2层 * ,....." ,如果这个时候你的数据中保存IP字段的长度很小(15个字节),数据库就报错了。
实际应用中,因为使用多层透明代理的情况比较少,所以这种用户并不多。
获取用户真实IP的方法
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
namespace Common
{
/// <summary>
/// IPAddress 的摘要说明
/// </summary>
public class IPAddress : System.Web.UI.Page
{
public static Int64 toDenaryIp ( string ip )
{
Int64 _Int64 = 0;
string _ip = ip;
if ( _ip.LastIndexOf ( "." ) > -1 )
{
string[] _iparray = _ip.Split ( '.' );
_Int64 = Int64.Parse ( _iparray.GetValue ( 0 ).ToString() ) * 256 * 256 * 256 + Int64.Parse ( _iparray.GetValue ( 1 ).ToString() ) * 256 * 256 + Int64.Parse ( _iparray.GetValue ( 2 ).ToString() ) * 256 + Int64.Parse ( _iparray.GetValue ( 3 ).ToString() ) - 1;
}
return _Int64;
}
/// <summary>
/// /ip十进制
/// </summary>
public static Int64 DenaryIp
{
get {
Int64 _Int64 = 0;
string _ip = IP;
if ( _ip.LastIndexOf ( "." ) > -1 )
{
string[] _iparray= _ip.Split ( '.' );
_Int64 = Int64.Parse ( _iparray.GetValue ( 0 ).ToString() ) * 256 * 256 * 256 + Int64.Parse ( _iparray.GetValue ( 1 ).ToString() ) * 256 * 256 + Int64.Parse ( _iparray.GetValue ( 2 ).ToString() ) * 256 + Int64.Parse ( _iparray.GetValue ( 3 ).ToString() )-1;
}
return _Int64;
}
}
public static string IP
{
get
{
string result = String.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if ( result != null && result != String.Empty )
{
//可能有代理
if ( result.IndexOf ( "." ) == -1 ) //没有"."肯定是非IPv4格式
result = null;
else
{
if ( result.IndexOf ( "," ) != -1 )
{
//有",",估计多个代理。取第一个不是内网的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 ) ) //代理即是IP格式
return result;
else
result = null; //代理中的内容 非IP,取IP
}
}
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;
}
}
//是否ip格式
public static bool IsIPAddress ( string str1 )
{
if ( str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15 ) return false;
string regformat = @"^\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}$";
Regex regex = new Regex ( regformat, RegexOptions.IgnoreCase );
return regex.IsMatch ( str1 );
}
}
}
希望本文所述对大家的C#程序设计有所帮助。


猜你喜欢
- 整合Spring Data JPAJPA (Java Persistence API)和 Spring Data 是两个范畴的概念。Hibe
- 目前html5发展非常迅速,很多native app都会嵌入到网页中,以此来适用多变的市场需求。但是android的webview默认支持的
- 持久层的那些事什么是 JDBCJDBC(JavaDataBase Connectivity)就是 Java 数据库连接, 说的直白点就是 使
- 一、引言“为什么我们需要掌握互操作技术的呢?” 对于这个问题的解释就是—&
- 很多初学者都对C中的指针很迷糊,希望这篇blog能帮助到大家:1.什么是“指针”:在执行C程序的时候,由于我们的数据是存储在内存中的。所以对
- Unity OnOpenAsset在Unity中,OnOpenAsset是一个非常有用的回调函数,它可以在用户双击资源文件时自动打开一个编辑
- 这篇文章主要介绍了JavaWeb如何实现禁用浏览器缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 概念所谓回文串,就是字符串反转以后和原串相同,如 abba 和 lippil。对于回文串还是比较容易去验证的,从字符数组的两端开始向中间靠拢
- 最近想关闭一个包的日志打印,经过一番研究实际上就一句话的事,一直没成功是因为name写错了。<logger name="pa
- 一、什么是抽象工厂模式为创建一组相关或相互依赖的对象提供一个接口,而且无需指定他们的具体类。抽象工厂模式是所有形态的工厂模式中最为抽象和最具
- 本文实例讲述了Android编程实现VideoView循环播放功能的方法。分享给大家供大家参考,具体如下:package com.hangc
- 一、前言先使用一个模板图片,在图片上添加图片或者文字都可以。二、依赖<dependency> <
- 本文实例为大家分享了Java实现五子棋的具体代码,供大家参考,具体内容如下任务概述:五子棋是全国智力运动会竞技项目之一,是一种两人对弈的纯策
- zookeeper集群配置多个实例共同构成一个集群对外提供服务以达到水平扩展的目的,每个服务器上的数据是相同的,每一个服务器均可以对外提供读
- 1.基本概念首先我们需要弄清楚几个概念:面向对象是什么、类是什么、对象又是什么?还是逐个来说1.1面向对象我们常说Java是面向对象的语言,
- 在activity级下使用this表示contextkotlin中取消了xxxActivity.this的用法,所以我们可以在activit
- 在项目里,我需要做一个Spring Boot结合Thymeleaf前端模版,结合JPA实现分页的演示效果。做的时候发现有些问题,也查了现有网
- 目录MeasureSpecLayoutParamViewViewGroupTextColumn使用总结
- 一、树概念及结构1.1 树的概念树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因 为
- 本文实例为大家分享了unity shader实现玻璃折射的具体代码,供大家参考,具体内容如下Shader "Unlit/rende