Determine Current GSM Network

This VB.NET code will work on Smartphone and Pocket PC Phone devices and return details of the current GSM operator (though it probably works on CDMA also). It relies on Alex Feinman’s excellent TAPI wrapper whish you can download here. Using the library we create a line object which we pass the handle of (line.hline) into lineGetCurrentOperator, one of the ExTAPI functions. For simplicity the structure is just passed as one big byte array then the strings are copied out from it and have trailing nulls chopped off.

‘gets the textual representation of the operator
Public Function GetCurrentOperator(ByVal line As OpenNETCF.TAPI.Line) As Operator
Dim result As Integer
Dim nullindex As Integer

‘stores operator details
Dim lo As New Operator

Dim buff(140) As Byte

BitConverter.GetBytes(-1).CopyTo(buff, 0)

‘call tapi method
result = lineGetCurrentOperator(line.hLine, buff)

If result < 0 Then
‘error encountered
Throw New System.Runtime.InteropServices.ExternalException(“TAPI Error getting operator: “ + result.ToString())
End If

lo.Index = BitConverter.ToInt32(buff, 0)
‘get status
lo.Status = BitConverter.ToInt32(buff, 4)
‘get valid fields
lo.ValidFields = CType(BitConverter.ToInt32(buff, 8), OperatorFormat)

‘long name
If (lo.ValidFields And OperatorFormat.AlphaLong) = OperatorFormat.AlphaLong Then
lo.LongName = System.Text.Encoding.Unicode.GetString(buff, 12, 64)
nullindex = lo.LongName.IndexOf(Chr(0))
If nullindex > -1 Then
lo.LongName = lo.LongName.Substring(0, nullindex)
End If
End If

‘copy short name
If (lo.ValidFields And OperatorFormat.AlphaShort) = OperatorFormat.AlphaShort Then
lo.ShortName = System.Text.Encoding.Unicode.GetString(buff, 76, 32)
nullindex = lo.ShortName.IndexOf(Chr(0))
If nullindex > -1 Then
lo.ShortName = lo.ShortName.Substring(0, nullindex)
End If
End If

‘copy num name
If (lo.ValidFields And OperatorFormat.Numeric) = OperatorFormat.Numeric Then
lo.NumName = System.Text.Encoding.Unicode.GetString(buff, 108, 32)
nullindex = lo.NumName.IndexOf(Chr(0))
If nullindex > -1 Then
lo.NumName = lo.NumName.Substring(0, nullindex)
End If
End If

Return lo

End Function

Declare Function lineGetCurrentOperator Lib “cellcore.dll” (ByVal hLine As IntPtr, ByVal operator As Byte()) As Integer

Public Class Operator

   Public Index As Integer
   Public ValidFields As OperatorFormat
   Public Status As Integer
   Public LongName As String
   Public ShortName As String
   Public NumName As String

End Class

Public Enum OperatorFormat
   None = &H0
   AlphaShort = &H1
   AlphaLong = &H2
   Numeric = &H4
End Enum