asp.Net(vb.net)実際のIPを取得する関数

3235 ワード

aspx vb.Netが実際のIPを取得する関数は以下の通りです.
 
  
<br>Public Function CheckIp(ByVal ip As String) As Boolean <br>Dim pat As String = "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$" <br>Dim reg As Regex = New Regex(pat) <br>if ip = "" Then <br>CheckIp = False <br>exit Function <br>end if <br>CheckIp = reg.IsMatch(ip) <br>End Function <br> <br>Public Function get_cli_ip() As String <br>If ( Not( System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP") Is Nothing) And CheckIp(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP")) = True) Then <br>get_cli_ip = System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP") <br>Exit Function <br>ElseIf Not(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR") Is Nothing) Then <br>Dim ips() As String = Split(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",") <br>For i As Integer = 0 To ips.Length - 1 <br>If CheckIp(Trim(ips(i))) = True Then <br>get_cli_ip = Trim(ips(i)) <br>Exit Function <br>End If <br>Next <br>End If <br>get_cli_ip = System.Web.HttpContext.Current.Request.ServerVariables("REMOTE_ADDR") <br>End Function <br>

完全なテストページ:
 
  



<br>Public Function CheckIp(ByVal ip As String) As Boolean <br>Dim pat As String = "^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$" <br>Dim reg As Regex = New Regex(pat) <br>if ip = "" Then <br>CheckIp = False <br>exit Function <br>end if <br>CheckIp = reg.IsMatch(ip) <br>End Function <br> <br>Public Function get_cli_ip() As String <br>If ( Not( System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP") Is Nothing) And CheckIp(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP")) = True) Then <br>get_cli_ip = System.Web.HttpContext.Current.Request.ServerVariables("HTTP_CLIENT_IP") <br>Exit Function <br>ElseIf Not(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR") Is Nothing) Then <br>Dim ips() As String = Split(System.Web.HttpContext.Current.Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",") <br>For i As Integer = 0 To ips.Length - 1 <br>If CheckIp(Trim(ips(i))) = True Then <br>get_cli_ip = Trim(ips(i)) <br>Exit Function <br>End If <br>Next <br>End If <br>get_cli_ip = System.Web.HttpContext.Current.Request.ServerVariables("REMOTE_ADDR") <br>End Function <br>



Untitled Page


Dim client_ip As String = get_cli_ip()
System.Web.HttpContext.Current.Response.Write(client_ip)
%>