VB.Net 2005 : FAQ. Working with Local Network Connections.
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: VB.Net 2005 : FAQ. Working with Local Network Connections.

  1. #1
    Join Date
    Jun 2005
    Location
    JHB South Africa
    Posts
    3,771

    VB.Net 2005 : FAQ. Working with Local Network Connections.

    Q: How do I retrieve a list of Local IP Address?

    A:
    Code:
    Imports System.Net 
     
    	Public Function GetLIPAdresses() As ArrayList 
    		Dim NetInterfaces() As NetworkInformation.NetworkInterface = NetworkInformation.NetworkInterface.GetAllNetworkInterfaces 
    		Dim IPList As New ArrayList 
    		Try 
    		 For Each NetInterface As NetworkInformation.NetworkInterface In NetInterfaces 
    				Dim infosDns As NetworkInformation.UnicastIPAddressInformationCollection = NetInterface.GetIPProperties.UnicastAddresses 
    				For Each address As NetworkInformation.UnicastIPAddressInformation In infosDns 
    					IPList.Add(address.Address.ToString) 
    				Next 
    			Next 
    		Catch ex As Exception 
    			MessageBox.Show("Error: " & ex.Message) 
    		End Try 
    	 Return IPList 
    	End Function
    'Code is thanks to aniskhan.

    Q: How do I init a TCP port for linking (Listen or Client)

    A:
    Code:
    Imports System.Net 
    Imports System.Text 
     
    	Public Enum TCP_State 
    		Listen 
    		Conect 
    		Client 
    	End Enum 
    	Private TCP_Listen As Sockets.TcpListener 
    	Private TCP_Client As Sockets.TcpClient 
    	Private Con_Method As TCP_State 
    	Public Event Socket_Error(ByVal Err As Exception) 
     
    	Public Function Init(ByVal Method As TCP_State, ByVal Port As Integer) As Boolean 
    		Try 
    			Con_Method = Method 
    			Select Case Con_Method 
    				Case TCP_State.Client 
    					TCP_Client = New Sockets.TcpClient 
    				Case TCP_State.Listen 
    					TCP_Listen = New Sockets.TcpListener(L_IP, Port) 
    					TCP_Listen.Start() 
    				Case Else 
    					Exit Function 
    			End Select 
    			C_Timer.Enabled = True 
    			Init = True 
    		Catch ex As Exception 
    			Init = False 
    			RaiseEvent Socket_Error(ex) 
    		End Try 
    	End Function
    Q: How do I connect to a listening TCP port (Client)

    A:
    Code:
    	Public Function Connect(ByVal HostAddress As IPAddress, ByVal Port As Integer) As Boolean 
    		Select Case Con_Method 
    			Case TCP_State.Client 
    				Try 
    					TCP_Client.Connect(HostAddress, Port) 
    					Return True 
    				Catch ex As Exception 
    					RaiseEvent Socket_Error(ex) 
    					Return False 
    				End Try 
    			Case Else 
    				Return False 
    		End Select 
    	End Function


    Q: How do I accept a connection request to a listening TCP port


    A: Because the Net class does not raise events, we need to use a timer to check if a connection request is pending, there after we can raise our own event.
    Code:
    	Private WithEvents C_Timer As System.Windows.Forms.Timer
    Code:
    	Public Event Connection_Request(ByVal Remote_IP As EndPoint) 
    	Private Con_Proc As Boolean 
    	Private Sub C_Timer_Elapsed(ByVal sender As Object, ByVal e As System.EventArgs) Handles C_Timer.Tick 
    		Select Case Con_Method 
    			Case TCP_State.Listen 
    			 If TCP_Listen.Pending Then 
    					TCP_Client = TCP_Listen.AcceptTcpClient 
    					RaiseEvent Connection_Request(TCP_Client.Client.RemoteEndPoint) 
    					Con_Method = TCP_State.Conect 
    					Con_Proc = True 
    					' Close listening port... We've got our conection 
    					TCP_Listen.Stop() 
    					TCP_Listen = Nothing 
    				End If 
    		End Select 
    	End Sub


    Q: How do I check the connection status during a TCP connection


    A: The following code snip runs in the same timer event as above.
    Code:
    	Public Event Connection_Complete(ByVal Remote_IP As EndPoint)
    Code:
    	Public Event Connection_Error()
    	Private Sub C_Timer_Elapsed(ByVal sender As Object, ByVal e As System.EventArgs) Handles C_Timer.Tick
    		Select Case Con_Method
    			Case TCP_State.Client, TCP_State.Conect
    				If Con_Proc Then
    					If TCP_Client.Available > 0 Then
    						Try
    							ReDim RecievedBytes(TCP_Client.Available - 1)
    							TCP_Client.GetStream.Read(RecievedBytes, 0, TCP_Client.Available)
    							Tot_Array = UBound(B_Data) + 1
    							ReDim Preserve B_Data(Tot_Array)
    							ReDim Preserve B_Sender(Tot_Array)
    							ReDim Preserve Raw_Data(Tot_Array)
    							B_Data(Tot_Array) = Encoding.ASCII.GetString(RecievedBytes)
    							B_Sender(Tot_Array) = RemoteIpEndPoint.Address
    							Raw_Data(Tot_Array).Data = RecievedBytes
    							I_Timer.Enabled = True
    					 Catch ex As Exception
    							RaiseEvent Socket_Error(ex)
    						End Try
    					End If
    					If Not TCP_Client.Connected Then
    						RaiseEvent Connection_Error()
    					End If
    				Else
    					If TCP_Client.Connected 
    						RaiseEvent Connection_Complete(TCP_Client.Client.RemoteEndPoint) 
    						Con_Proc = True 
    					End If 
    			 End If 
    		End Select 
    	End Sub






  2. #2
    Join Date
    Jun 2005
    Location
    JHB South Africa
    Posts
    3,771

    Re: VB.Net 2005 : FAQ. Working with Local Network Connections.

    The following FAQ questions refer to open TCP Connections

    Q: How do I send my Data through an open connection?

    A: It is the prefered method to send data in a byte array.
    Code:
        Public Function Send(ByVal Byte_ary() As Byte) As Boolean
            Try
                Select Case Con_Method
                    Case TCP_State.Client, TCP_State.Conect
                        TCP_Client.GetStream.Write(Byte_ary, 0, Byte_ary.GetUpperBound(0) + 1)
                    Case Else
                        Send = False
                End Select
            Catch ex As Exception
                Send = False
                RaiseEvent Socket_Error(ex)
            End Try
        End Function
    When the data is a string type variable the following can be used to send
    Code:
    TCP_Client.GetStream.Write(Encoding.ASCII.GetBytes(Data), 0, Encoding.ASCII.GetByteCount(Data))
    Q: How do I Recieve my Data from an open connection?

    A: Again because the Net class does not raise events we need to use a timer (even the same timer used to check for connection requests.)
    Code:
        Public Event Data_Arrival(ByVal Data As String, ByVal Source As IPAddress)
        Private B_Data As String
        Private B_Sender As IPAddress
        Private RecievedBytes() As Byte
    
                        If TCP_Client.Available > 0 Then
                            Try
                                ReDim RecievedBytes(TCP_Client.Available - 1)
                                TCP_Client.GetStream.Read(RecievedBytes, 0, TCP_Client.Available)
                                B_Data = Encoding.ASCII.GetString(RecievedBytes)
                                B_Sender = RemoteIpEndPoint.Address
                                RaiseEvent Data_Arrival(B_Data, B_Sender)
                            Catch ex As Exception
                                RaiseEvent Socket_Error(ex)
                            End Try
                        End If
    Q: How do I close a TCP Connection.

    A: The close command is dependant on the connection state of the TCP port.
    Code:
        Public Function Close() As Boolean
            Try
                Select Case Con_Method
                    Case TCP_State.Client
                        TCP_Client.Close()
                        TCP_Client = Nothing
                    Case TCP_State.Listen
                        TCP_Listen.Stop()
                        TCP_Listen = Nothing
                End Select
                C_Timer.Enabled = False
                Close = True
            Catch ex As Exception
                Close = False
            End Try
        End Function
    Articles VB6 : Break the 2G limit - Animation 1, 2 VB.NET : 2005/8 : Moving Images , Animation 1 , 2 , 3 , User Controls
    WPF Articles : 3D Animation 1 , 2 , 3
    Code snips: VB6 Hex Edit, IP Chat, Copy Prot., Crop, Zoom : .NET IP Chat (V4), Adv. ContextMenus, click Hotspot, Scroll Controls
    Find me in ASP.NET., VB6., VB.NET , Writing Articles, My Genealogy, Forum
    All VS.NET: posts refer to VS.NET 2008 (Pro) unless otherwise stated.

  3. #3
    Join Date
    Jun 2005
    Location
    JHB South Africa
    Posts
    3,771

    Re: VB.Net 2005 : FAQ. Working with Local Network Connections.

    The following FAQ Questions apply to UDP connections.

    Q: How do I send data to a UDP Socket?

    A: As UDP is not tied to a specific destination, you need to specify the destination IP Address and port. Also again it is the preffered method to send data in a byte array.
    Code:
        Public Function Send(ByVal Byte_Ary() As Byte, ByVal Address As IPEndPoint) As Boolean
            Try
                UDP_Sock.Send(Byte_Ary, Byte_Ary.GetUpperBound(0) + 1, Address)
                Send = True
            Catch ex As Exception
                Send = False
                RaiseEvent Socket_Error(ex)
            End Try
        End Function
    If your data is in a string variable the following can be used to send data
    Code:
    UDP_Sock.Send(Encoding.ASCII.GetBytes(Data), Len(Data), Address)
    Q: How do I recieve data from a UDP Socket?

    A: Again because no events are raised by the Net Class, the following code needs to be in a timer.
    Code:
            If UDP_Sock.Available > 0 Then
                Try
                    RecievedBytes = UDP_Sock.Receive(RemoteIpEndPoint)
                    B_Data = Trim(Encoding.ASCII.GetString(RecievedBytes))
                    B_Sender = RemoteIpEndPoint.Address
                    RaiseEvent Data_Arrival(B_Data, B_Sender)
                Catch ex As Exception
                    RaiseEvent Socket_Error(ex)
                End Try
            End If
    Q: How do I close a UDP Socket?

    A: Because the UDP socket is not bound or connected, does not have a state, you only need to close the socket
    Code:
        Public Function Close() As Boolean
            Try
                UDP_Sock.Close()
                UDP_Sock = Nothing
                Close = True
            Catch ex As Exception
                Close = False
            End Try
        End Function
    Articles VB6 : Break the 2G limit - Animation 1, 2 VB.NET : 2005/8 : Moving Images , Animation 1 , 2 , 3 , User Controls
    WPF Articles : 3D Animation 1 , 2 , 3
    Code snips: VB6 Hex Edit, IP Chat, Copy Prot., Crop, Zoom : .NET IP Chat (V4), Adv. ContextMenus, click Hotspot, Scroll Controls
    Find me in ASP.NET., VB6., VB.NET , Writing Articles, My Genealogy, Forum
    All VS.NET: posts refer to VS.NET 2008 (Pro) unless otherwise stated.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center