How to Connect mobile with the pc - c#

I'm doing a desktop academic project one of the requirment of this project is to allert the user on mobile by sms and this sms should be sent by a mobile that is connected with the pc. I don't know the way how can i do it. When i did google search here i got the gsm modems gateways one kind of solution to send sms through pc. But they are not free. Then Nokia Conectivity SDK is another way but it is not compatible with Visual Studio2010. I got this example on a website but the sender had said at the end there are errors in my code.
Option Explicit On
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.load
End Sub
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Function SendSMS(ByVal CellNumber As String, ByVal SMSMessage As String) As Boolean
Dim MyMessage As String = Nothing
'Check if Message Length <= 160
If SMSMessage.Length <= 160 Then
MyMessage = SMSMessage
Else
MyMessage = Mid(SMSMessage, 1, 160)
End If
If IsOpen = True Then
SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
_ContSMS = False
SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
_Continue = False
RaiseEvent Sending(False)
End If
End Function
Private Sub ReadPort()
Dim SerialIn As String = Nothing
Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
Dim SMSMessage As String = Nothing
Dim Strpos As Integer = 0
Dim TmpStr As String = Nothing
While SMSPort.IsOpen = True
If (SMSPort.BytesToRead <> 0) And (SMSPort.IsOpen = True) Then
While SMSPort.BytesToRead <> 0
SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
SerialIn = SerialIn & System.Text.Encoding.ASCII.GetString(RXBuffer)
If SerialIn.Contains(">") = True Then
_ContSMS = True
End If
If SerialIn.Contains("+CMGS:") = True Then
_Continue = True
RaiseEvent Sending(True)
_Wait = False
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
RaiseEvent DataReceived(SerialIn)
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
End Sub
Public ReadOnly Property IsOpen() As Boolean
Get
If SMSPort.IsOpen = True Then
IsOpen = True
Else
IsOpen = False
End If
End Get
End Property
Public Sub Open()
If IsOpen = False Then
SMSPort.Open()
ReadThread.Start()
End If
End Sub
Public Sub Close()
If IsOpen = True Then
'SMSPort = New SMSCOMMS("COM1")
'SMSEngine.Open()
'SMSEngine.SendSMS("919888888888", "SMS Testing")
'SMSEngine.Close()
SMSPort.Close()
End If
End Sub
End Class
but it is in vb.net i have not command in it. is it work?
Kindly Give me some idea, example I'm doing it in winform using c sharp.

hey i used GSMCOMM library and that works for me to send and receive sms using Computer. download it from google and see its examples to check how it works.
here are some links that help
GSMCOMM Send and recieve SMS Using GSM Modem
from here you can download GSMCOMM library

I'm not sure if you want a way to connect to a phone or a way to send an sms from a pc so I'll give both.
To connect to a phone (if it has data and an android or IOS or something where you can directly modify code) you can create a socket connection from your pc to your phone. I have done this in android aps before and it works good.
If you simply need to send an sms from your computer and you know the carrier just send an email using this list http://www.mutube.com/projects/open-email-to-sms/gateway-list/

Related

VB.Net MasterPage Page.PreLoad Property not found

I am trying to implement Cross-Site Request Forgery (CSRF) using Microsoft .Net ViewStateUserKey and Double Submit Cookie. For more please visit this link
The above code is in C# and i am converting this into VB.Net. Now The problem is that in this code there is a line
Page.PreLoad += master_Page_PreLoad;
When i try to convert the same line in VB.Net it does not find any such event Page.PreLoad
Please help how can i do this.
Thanks
The C# MasterPage template converted to VB looks like this:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
End Class
I believe the specific line you're looking for is AddHandler Page.PreLoad, AddressOf master_Page_PreLoad.
For future reference, if you're looking to convert C# code to VB, or vice versa, there is a pretty great Telerik tool for that which can be found here: http://converter.telerik.com/. In order to get the code I posted above, I simply ran the C# template through there.
You can straight away create the method,
Private Sub Page_PreRender(ByVal sender As System.Object, ByVal e As System.EventArgs)
If Not IsPostBack Then
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, String.Empty)
Else
If CStr(ViewState(AntiXsrfTokenKey)) <> _antiXsrfTokenValue OrElse CStr(ViewState(AntiXsrfUserNameKey)) <> (If(Context.User.Identity.Name, String.Empty)) Then
Throw New InvalidOperationException("Validation of " & "Anti-XSRF token failed.")
End If
End If
End Sub
No need to address this
Page.PreLoad += master_Page_PreLoad;

Cookie set and read not working in IE9 using asp.net code?

IE 9 is setting cookie values in browser even after changing privacy settings. What is the next option to save cookies in IE?
see below my code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
If Not Request.Cookies("RememberMe") Is Nothing Then
'this if condition is failing, it never executes and working in chrome.
End If
End If
Response.Cache.SetExpires(DateTime.Parse(DateTime.Now.ToString()))
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Cache.SetNoStore()
Response.AppendHeader("Pragma", "no-cache")
End Sub
Protected Sub imgLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
If Page.IsValid() Then
If Not user Is Nothing Then
FormsAuthentication.RedirectFromLoginPage(strUserID, False)
If (chkRememberMe.Checked) Then
Helper.StoreRememberMe(strUserID, ddlCompany.SelectedItem.Text)
ElseIf Not Request.Cookies("RememberMe") Is Nothing Then
Helper.DeleteCookie("RememberMe")
End If
Session("userInfo") = user
Response.Redirect("~/home.aspx")
End If
End If
End Sub
Public Shared Sub StoreRememberMe(ByVal username As String, ByVal company As String)
Dim rememberMe As New HttpCookie("RememberMe")
rememberMe.Values.Add("user", username)
rememberMe.Values.Add("company", company)
rememberMe.Expires = DateTime.Now.AddDays(30)
'cookie Expires ;
HttpContext.Current.Response.AppendCookie(rememberMe)
End Sub

pos for.net in windows 7 vb.net

I am using microsoft POS for .net dll and I am converting this part to vb.net from a HOL sample barcode reading tutorial written in c# found here.
EDIT:The device list shows and popup window shows (the activate button is pressed and scanner input is tested)but the txteventhistory is not update even when scanner emulator is used and i suspect the said part is the culprit. thank you for the response
{
Action<string> updateEventHistoryAction = new Action<string>(p => { txtEventHistory.Text = p; });
txtEventHistory.Invoke(updateEventHistoryAction, newEvent);
}
from this
void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
string data = encoder.GetString(activeScanner.ScanDataLabel);
Action<string> updateScanDataLabelAction = new Action<string>(p => {txtScanDataLabel.Text = p;});
txtScanDataLabel.Invoke(updateScanDataLabelAction, data);
// Display the encoding type
string dataType = activeScanner.ScanDataType.ToString();
Action<string> updateScanDataTypeLabelAction = new Action<string>(p => { txtScanDataType.Text = p; });
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType);
// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}
the conversion tool in #develop yielded the one below but i don't think it's correct
Dim updateScanDataLabelAction As New Action(Of String)(function (p)
txtScanDataLabel.Text = p
end function)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
I tried converting it to but not quite there i think, though it
Private Sub activeScanner_DataEvent(sender As Object, e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction append As New Action(Of String))
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
here is the whole code
Imports Microsoft.PointOfService
Imports System.Collections
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Namespace POS
Partial Public Class ScannerLab
Inherits Form
Private explorer As PosExplorer
Private scannerList As DeviceCollection
Private scannerList1 As DeviceCollection
Private activeScanner As Scanner
Public Sub New()
InitializeComponent()
End Sub
Private Sub ScannerLab_Load(ByVal sender As Object, ByVal e As EventArgs)handles mybase.load
explorer = New PosExplorer()
scannerList1 = explorer.GetDevices()
bsdevices.DataSource = scannerList1
cboDevices.DisplayMember = scannerList1.ToString()
scannerList = explorer.GetDevices(DeviceType.Scanner)
devicesBindingSource.DataSource = scannerList
lstDevices.DisplayMember = scannerList.ToString()
End Sub
Private Sub btnActivateDevice_Click(ByVal sender As Object, ByVal e As EventArgs) handles btnActivateDevice.Click
If lstDevices.SelectedItem IsNot Nothing Then
ActivateScanner(DirectCast(lstDevices.SelectedItem, DeviceInfo))
End If
End Sub
Private Sub reportFailure()
Throw New Exception("The method or operation is not implemented.")
End Sub
Private Sub ActivateScanner(ByVal selectedScanner As DeviceInfo)
'Verifify that the selectedScanner is not null
' and that it is not the same scanner already selected
If selectedScanner IsNot Nothing AndAlso Not selectedScanner.IsDeviceInfoOf(activeScanner) Then
' Configure the new scanner
DeactivateScanner()
' Activate the new scanner
UpdateEventHistory(String.Format("Activate Scanner: {0}", selectedScanner.ServiceObjectName))
Try
activeScanner = DirectCast(explorer.CreateInstance(selectedScanner), Scanner)
activeScanner.Open()
activeScanner.Claim(1000)
activeScanner.DeviceEnabled = True
AddHandler activeScanner.DataEvent, AddressOf activeScanner_DataEvent
AddHandler activeScanner.ErrorEvent, AddressOf activeScanner_ErrorEvent
activeScanner.DecodeData = True
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log error and set the active scanner to none
UpdateEventHistory(String.Format("Activation Failed: {0}", selectedScanner.ServiceObjectName))
activeScanner = Nothing
End Try
End If
End Sub
Private Sub DeactivateScanner()
If activeScanner IsNot Nothing Then
' We have an active scanner, lets log that we are
' about to close it.
UpdateEventHistory("Deactivate Current Scanner")
Try
' Close the active scanner
activeScanner.Close()
Catch generatedExceptionName As PosControlException
' Log any error that happens
UpdateEventHistory("Close Failed")
Finally
' Don't forget to set activeScanner to null to
' indicate that we no longer have an active
' scanner configured.
activeScanner = Nothing
End Try
End If
End Sub
Private Sub activeScanner_DataEvent(ByVal sender As Object, ByVal e As DataEventArgs)
UpdateEventHistory("Data Event")
Dim encoder As New ASCIIEncoding()
Try
' Display the ASCII encoded label text
Dim data As String = encoder.GetString(activeScanner.ScanDataLabel)
Dim updateScanDataLabelAction As New Action(Of String)(AddressOf p)
txtScanDataLabel.Invoke(updateScanDataLabelAction, data)
' Display the encoding type
Dim dataType As String = activeScanner.ScanDataType.ToString()
Dim updateScanDataTypeLabelAction As New Action(Of String)(AddressOf p)
txtScanDataType.Invoke(updateScanDataTypeLabelAction, dataType)
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("DataEvent Operation Failed")
End Try
End Sub
Private Sub p(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub q(ByVal text As String)
txtScanDataType.Text = text
End Sub
Private Sub UpdateEventHistory(ByVal newEvent As String)
If txtEventHistory.InvokeRequired Then
Dim updateEventHistoryAction As New Action(Of String)(AddressOf q)
txtEventHistory.Invoke(updateEventHistoryAction, newEvent)
Else
txtEventHistory.Text = (Convert.ToString(newEvent) & System.Environment.NewLine) + txtEventHistory.Text
End If
End Sub
Private Sub activeScanner_ErrorEvent(ByVal sender As Object, ByVal e As DeviceErrorEventArgs)
UpdateEventHistory("Error Event")
Try
' re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = True
Catch generatedExceptionName As PosControlException
' Log any errors
UpdateEventHistory("ErrorEvent Operation Failed")
End Try
End Sub
EDIT: updated the code

How can I force web browser control to remember proxy credentials setting?

I'm using .net web browser control to open an url in new window through proxy with credentials. I use this code for that:
Public Function AppendHeader(ByRef OriginalHeader As String, ByVal Addition As String) As Boolean
If OriginalHeader <> "" Then
OriginalHeader = OriginalHeader + vbNewLine
End If
OriginalHeader = OriginalHeader + Addition
OriginalHeader.Trim(vbNewLine.ToCharArray)
End Function
Public Function Base64Enc(ByRef s As String) As String
Base64Enc = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(s))
End Function
Public Sub Navigate()
Dim webBrowser As WebBrowser = New WebBrowser()
Dim headers As String = ""
AppendHeader(headers, "Proxy-Authorization: Basic " & Base64Enc("user:pass"))
'AppendHeader(headers, "Authorization: Basic " & Base64Enc("user:pass"))
webBrowser.Navigate("http://stackoverflow.com", Guid.NewGuid().ToString(), Nothing, headers)
End Sub
This code helps to hide Windows Security window at the first time, but if loading web page sends requests to other urls this window shows again and again (you can see it on a screenshot below).
So what can I do to solve this problem?
(I'm using winforms and vb.net, but C# is suitable too)
Give this a try I am unable to test it :)
Private Sub webBrowser_Navigating(ByVal sender As Object, ByVal e As WebBrowserNavigatingEventArgs)
Dim credentials As New System.Net.NetworkCredential("user", "pwd", "MyDomain")
Dim proxy As New System.Net.WebProxy("127.0.1.2", 80)
If proxy Is Nothing Then
e.Cancel = True
End If
End Sub

Identify if request is coming from local network (intranet)

I need to identify if a request comes from Internet or Intranet using either client-side or server-side.
The problem I'm trying to solve is: our web site can be accessed from internet and intranet. The intranet user (user inside company), does not have access to internet. We are using Google Anylitics, when intranet user access the page, the page take so long to upload because it tries to download (ga) JavaScript file generated from Google.
Any solution?
You can check the ip address of a user. Private ip4 address always start with either 10., or 172., or 192.* ... more info on private networks here.
You can also make Google Analytics load Asynchronous.
***************** UPDATE - PLEASE READ *************************************
As #igor-turman has correctly pointed out, that only a portion of the "172" and the "192" address ranges are designated for private use.
The remaining ip addresses starting with 172 and 192 ARE PUBLIC.
Here is the regex expression to check for private IP addresses:
(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)
You can test this regex on regexpal.com here.
This is how I would do the ip check:
string ipString = System.Web.HttpContext.Current.Request.UserHostAddress;
byte[] ipBytes = System.Net.IPAddress.Parse(ipString).GetAddressBytes();
int ip = System.BitConverter.ToInt32(ipBytes, 0);
// your network ip range
string ipStringFrom = "192.168.1.0";
byte[] ipBytesFrom = System.Net.IPAddress.Parse(ipStringFrom).GetAddressBytes();
int ipFrom = System.BitConverter.ToInt32(ipBytesFrom, 0);
string ipStringTo = "192.168.1.255";
byte[] ipBytesTo= System.Net.IPAddress.Parse(ipStringTo).GetAddressBytes();
int ipTo = System.BitConverter.ToInt32(ipBytesFrom, 0);
bool clientIsOnLAN = ipFrom >= ip && ip <= ipTo;
If you have multiple subnets, just do the same for them (from, to), then add to the bool condition above. I just realized that, in your case, the above may be an overkill.
Alternatively, for you, it might be as simple as:
bool isOnLAN = System.Web.HttpContext.Current.Request.UserHostAddress.StartsWith("192.168.1.")
Necromancing:
None of the answers are good or correct.
You can convert the IP (IPv4 only - IPv6 is UInt128) into a UInt32 value, and then you can check if the requesting IP is somewhere in the private IP ranges:
e.g. you can use that to set the cookies to "Secure", if it's not intranet.
For Each thisCookie As System.Web.HttpCookie In response.Cookies
thisCookie.HttpOnly = True
Dim ipString As String = System.Web.HttpContext.Current.Request.UserHostAddress
If Not IPv4Info.IsPrivateIp(ipString) Then
thisCookie.Secure = True
End If
Next thisCookie
VB.NET Class, which you can convert into C# yourselfs (http://converter.telerik.com)
Public Class IPv4Info
Private Class IPv4Range
Public RangeStart As UInt32
Public RangeEnd As UInt32
End Class
' https://en.wikipedia.org/wiki/Private_network
' https://tools.ietf.org/html/rfc1918
' 192.168.0.0 - 192.168.255.255 (65,536 IP addresses)
' 172.16.0.0 - 172.31.255.255 (1,048,576 IP addresses)
' 10.0.0.0 - 10.255.255.255 (16,777,216 IP addresses)
Private Shared Rng127 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("127.0.0.0"), .RangeEnd = GetIpNum("127.255.255.255")}
Private Shared Rng192 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("192.168.0.0"), .RangeEnd = GetIpNum("192.168.255.255")} ' CIDR: 192.168.0.0/16 (255.255.0.0)
Private Shared Rng172 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("172.16.0.0"), .RangeEnd = GetIpNum("172.31.255.255")} ' CIDR: 172.16.0.0/12 (255.240.0.0)
Private Shared Rng10 As IPv4Range = New IPv4Range() With {.RangeStart = GetIpNum("10.0.0.0"), .RangeEnd = GetIpNum("10.255.255.255")} ' CIDR: 10.0.0.0/8 (255.0.0.0)
' http://stackoverflow.com/questions/36831/how-do-you-parse-an-ip-address-string-to-a-uint-value-in-c
Public Shared Function GetIpNum(ipString As String) As UInt32
Dim ipAddress__1 As System.Net.IPAddress = System.Net.IPAddress.Parse("some.ip.address")
Dim ipBytes As Byte() = ipAddress__1.GetAddressBytes()
Dim ip As UInt32 = CUInt(ipBytes(0)) << 24
ip += CUInt(ipBytes(1)) << 16
ip += CUInt(ipBytes(2)) << 8
ip += CUInt(ipBytes(3))
Return ip
End Function
Public Shared Function isIn127(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn127(ip)
End Function
Public Shared Function isIn127(x As UInt32) As Boolean
If x >= Rng127.RangeStart AndAlso x <= Rng127.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn192(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn192(ip)
End Function
Public Shared Function isIn192(x As UInt32) As Boolean
If x >= Rng192.RangeStart AndAlso x <= Rng192.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn172(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn172(ip)
End Function
Public Shared Function isIn172(x As UInt32) As Boolean
If x >= Rng172.RangeStart AndAlso x <= Rng172.RangeEnd Then
Return True
End If
Return False
End Function
Public Shared Function isIn10(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return isIn10(ip)
End Function
Public Shared Function isIn10(x As UInt32) As Boolean
If x >= Rng10.RangeStart AndAlso x <= Rng10.RangeEnd Then
Return True
End If
Return False
End Function
' string ipString = System.Web.HttpContext.Current.Request.UserHostAddress;
Public Shared Function IsPrivateIp(ipString As String) As Boolean
Dim ip As UInt32 = GetIpNum(ipString)
Return IsPrivateIp(ip)
End Function
Public Shared Function IsPrivateIp(ip As UInt32) As Boolean
If isIn127(ip) OrElse isIn192(ip) OrElse isIn172(ip) OrElse isIn10(ip) Then
Return True
End If
Return False
End Function
End Class
Note: For doing this with UInt128, there's a good implementation of UInt128 in NaCl.NET.
Use the Request.UserHostAddress property to determine whether the request came from a public or private network

Categories