locked
help fix proxy vb.net RRS feed

  • Question

  • why not work

    Imports System.Net.Sockets
    Imports System.Threading
    Imports System.Net
    
    Module Module1
    
     
    
        Sub main()
            listeners = ArrayList.Synchronized(listeners)
            sockets = ArrayList.Synchronized(sockets)
    
            '#Region "print starting parameters"
            Console.WriteLine("PACKET_BUFFSIZE = {0}", PACKET_BUFFSIZE)
            Console.WriteLine("LOCAL_OUT_IPADDR = {0}", LOCAL_OUT_IPADDR)
            Console.WriteLine("TARGET_IPADDR = {0}", TARGET_IPADDR)
            Console.Write("TARGET_PORTS: ")
            For Each port As Integer In TARGET_PORTS
                Console.Write("{0} ", port)
            Next
            Console.WriteLine(vbLf)
      
            Dim ap_arr As IPAddress() = Dns.GetHostAddresses(Dns.GetHostName())
            Dim target_addr As IPAddress = Dns.Resolve(TARGET_IPADDR).AddressList(0)
            Dim local_out_addr As IPAddress = IPAddress.Parse("192.168.1.88")
    
            Dim interface_no As Integer = 0
            Console.WriteLine("local active IP4 interfaces:")
            For Each ia As IPAddress In ap_arr
                If ia.AddressFamily = AddressFamily.InterNetwork Then
                    Console.WriteLine(" {0}: " + ia.ToString(), System.Math.Max(System.Threading.Interlocked.Increment(interface_no), interface_no - 1))
                End If
    
                ' set addresses if available
                If ia.ToString() = TARGET_IPADDR Then
                    ' set target
                    target_addr = ia
                ElseIf ia.ToString() = LOCAL_OUT_IPADDR Then
                    ' set local
                    local_out_addr = ia
                End If
            Next
            Console.WriteLine()
            Console.WriteLine("target interface address set to {0}", target_addr.ToString())
            Console.WriteLine("local outgoing interface address set to {0}", local_out_addr.ToString())
            If target_addr.ToString() <> TARGET_IPADDR Then
                Console.WriteLine()
                Console.WriteLine("error: target interface not match")
                Console.WriteLine("exit:  interface unavailable")
                Console.ReadKey(True)
                Return
            End If
            If local_out_addr.ToString() <> LOCAL_OUT_IPADDR Then
                Console.WriteLine()
                Console.WriteLine("error: local interface not match")
                Console.WriteLine("exit:  interface unavailable")
                Console.ReadKey(True)
                Return
            End If
            Console.WriteLine("--ok--" & vbLf)
            Console.ForegroundColor = ConsoleColor.Yellow
            Console.WriteLine("ANY KEY TO STOP AND CLOSE ALL" & vbLf)
            Console.ResetColor()
            '#End Region
    
            '#Region "run listeners"
            ' Start new listener for every port in TARGETS_PORT array asynchronously.
            ' An object is needed as a parameter for Thread.
            For i As Integer = 0 To TARGET_PORTS.Length - 1
                Dim o As Object() = New Object() {DirectCast(target_addr, Object), DirectCast(local_out_addr, Object), DirectCast(TARGET_PORTS(i), Object), DirectCast(i, Object)}
                Dim t As New Thread(New ParameterizedThreadStart(AddressOf RunListenerThread))
                t.Start(o)
            Next
            '#End Region
    
            '#Region "close all and exit"
            Console.ReadKey(True)
            Console.WriteLine()
            Try
                Console.WriteLine("closing listeners..")
                For Each l As TcpListener In listeners
                    l.[Stop]()
                Next
                Console.WriteLine("closing sockets..")
                For Each s As SocketStateObj In sockets
                    s.in_socket.Close()
                    s.out_socket.Close()
                Next
            Catch generatedExceptionName As Exception
            End Try
            Console.WriteLine("--ok--")
            Console.ReadKey(True)
            '#End Region
        End Sub
            Public Const PACKET_BUFFSIZE As Integer = 2048
            ' packet buffer in bytes
            Private Const LOCAL_OUT_IPADDR As String = "192.168.1.88"
            ' active localhost external address (set your one)
        Private Const TARGET_IPADDR As String = "138.197.83.21"
            ' destination address (google.com)
            '8080
        Private ReadOnly TARGET_PORTS As Integer() = New Integer() {8080}
    
            Public packet_no As Integer = 0
            ' packet counter
            Private listeners As New ArrayList()
            ' array of references to all listeners
            Private sockets As New ArrayList()
    
    
            Private Sub RunListenerThread(o As Object)
                Dim oa As Object() = DirectCast(o, Object())
                Dim listNo As Integer = CInt(oa(3))
                Try
                    RunListener(DirectCast(oa(0), IPAddress), DirectCast(oa(1), IPAddress), CInt(oa(2)), listNo)
                Catch generatedExceptionName As ThreadAbortException
                    ' <-- listener exception handling code -->
    
                    'Console.WriteLine("listener {0} exception: {1}", listNo, ex.Message);
                Catch ex As Exception
                End Try
            End Sub
    
    
            Private Sub RunListener(listenerInterface As IPAddress, outgoingInterface As IPAddress, listenerPort As Integer, listNo As Integer)
                Dim listener As New TcpListener(listenerInterface, listenerPort)
                listeners.Add(listener)
                listener.Start()
                Console.WriteLine("listener {0} started at {1}:{2}", listNo, listenerInterface.ToString(), listenerPort)
    
                While True
                    Console.WriteLine("listener {0} is waiting for a new client", listNo)
                    Dim incoming_socket As Socket = listener.AcceptSocket()
                    Console.WriteLine("listener {0}: client connected", listNo)
    
                    ' connecting remote host
                    Console.WriteLine("listener {0} is connecting to remote host {1}:{2}", listNo, TARGET_IPADDR, listenerPort)
                    Dim remote_socket As Socket = ConnectSocket(New IPEndPoint(outgoingInterface, 0), TARGET_IPADDR, listenerPort)
                    If remote_socket Is Nothing Then
                        Console.WriteLine("listener {0}: outgoing connection failed", listNo)
                        Continue While
                    End If
                    Console.WriteLine("listener {0}: connected to remote host {1}:{2}", listNo, TARGET_IPADDR, listenerPort)
    
                    ' begin receive on input
                    Dim iso As New SocketStateObj(incoming_socket, remote_socket)
                    sockets.Add(iso)
                    incoming_socket.BeginReceive(iso.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), iso)
    
                    ' begin receive on output
                    Dim oso As New SocketStateObj(remote_socket, incoming_socket)
                    sockets.Add(oso)
                    remote_socket.BeginReceive(oso.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), oso)
                End While
            End Sub
    
    
            Private Sub Read_Callback(ar As IAsyncResult)
                Dim s1 As Socket = Nothing
                Dim s2 As Socket = Nothing
                Try
                    ' retrieve SocketStateObj
                    Dim so As SocketStateObj = DirectCast(ar.AsyncState, SocketStateObj)
                    s1 = so.in_socket
                    s2 = so.out_socket
                    Dim count As Integer = s1.EndReceive(ar)
    
                    If count > 0 Then
                        ' copy of buffer data
                        Dim tmpbuff As Byte() = New Byte(PACKET_BUFFSIZE - 1) {}
                        so.buffer.CopyTo(tmpbuff, 0)
    
                        ' async. wait for next packet
                        s1.BeginReceive(so.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), so)
    
                        ' <-- packet filtering -->
    
                        '#Region "show packet info"
                        Console.ForegroundColor = ConsoleColor.Cyan
                        Console.WriteLine("[{0}] packet {1} -> S: {2}  D: {3}  len: {4}", DateTime.Now.ToString("HH:mm:ss"), System.Math.Max(System.Threading.Interlocked.Increment(packet_no), packet_no - 1), s2.LocalEndPoint.ToString(), s1.LocalEndPoint.ToString(), count)
                        Console.ResetColor()
                        '#End Region
    
                        ' send packet to destination (if not filtered)
    
                        ' <-- packet injection or re-sending -->
                        s2.Send(tmpbuff, 0, count, SocketFlags.None)
                    Else
                        ' close connections if packet has empty data                    
                        Console.WriteLine("connection {0} <-> {1} closed", s2.LocalEndPoint.ToString(), s1.LocalEndPoint.ToString())
                        s1.Close()
                        s2.Close()
                    End If
                Catch ex As Exception
                    ' <-- socket exception handling code -->
    
                    'Console.WriteLine("Read_Callback exception: {0}", ex.Message);
                    Try
                        s1.Close()
                        s2.Close()
                    Catch generatedExceptionName As Exception
                    End Try
                End Try
            End Sub
    
    
    
            Private Function ConnectSocket(localEndpoint As IPEndPoint, remoteServer As String, remotePort As Integer) As Socket
                Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                s.Bind(localEndpoint)
                s.Connect(remoteServer, remotePort)
                Return s
            End Function
    
    
    
       
        ''' <summary>
        ''' State object class for AsyncCallback delegation
        ''' </summary>
    
        Public Class SocketStateObj
            Public Shared ReadOnly BUFF_SIZE As Integer = Module1.PACKET_BUFFSIZE
            Public in_socket As Socket = Nothing
            Public out_socket As Socket = Nothing
            Public buffer As Byte() = New Byte(BUFF_SIZE - 1) {}
    
            Public Sub New(in_socket As Socket)
                Me.in_socket = in_socket
            End Sub
    
            Public Sub New(in_socket As Socket, out_socket As Socket)
                Me.in_socket = in_socket
                Me.out_socket = out_socket
            End Sub
        End Class
    
    
    End Module



    Tuesday, September 5, 2017 3:40 PM

All replies

  • First this is C# and needs to be move to the appropriate forum. Second, you need to ask a question or indicate what the problem is with the code.

    Paul ~~~~ Microsoft MVP (Visual Basic)

    Tuesday, September 5, 2017 3:55 PM
  • Next time if not somebody has already replies, you can remove your question in top of the message. 

    Success
    Cor

    Tuesday, September 5, 2017 5:14 PM
  • why nNo data received on the proxy

    Imports System.Net.Sockets
    Imports System.Threading
    Imports System.Net
    
    Module Module1
    
     
    
        Sub main()
            listeners = ArrayList.Synchronized(listeners)
            sockets = ArrayList.Synchronized(sockets)
    
            '#Region "print starting parameters"
            Console.WriteLine("PACKET_BUFFSIZE = {0}", PACKET_BUFFSIZE)
            Console.WriteLine("LOCAL_OUT_IPADDR = {0}", LOCAL_OUT_IPADDR)
            Console.WriteLine("TARGET_IPADDR = {0}", TARGET_IPADDR)
            Console.Write("TARGET_PORTS: ")
            For Each port As Integer In TARGET_PORTS
                Console.Write("{0} ", port)
            Next
            Console.WriteLine(vbLf)
      
            Dim ap_arr As IPAddress() = Dns.GetHostAddresses(Dns.GetHostName())
            Dim target_addr As IPAddress = Dns.Resolve(TARGET_IPADDR).AddressList(0)
            Dim local_out_addr As IPAddress = IPAddress.Parse("192.168.1.88")
    
            Dim interface_no As Integer = 0
            Console.WriteLine("local active IP4 interfaces:")
            For Each ia As IPAddress In ap_arr
                If ia.AddressFamily = AddressFamily.InterNetwork Then
                    Console.WriteLine(" {0}: " + ia.ToString(), System.Math.Max(System.Threading.Interlocked.Increment(interface_no), interface_no - 1))
                End If
    
                ' set addresses if available
                If ia.ToString() = TARGET_IPADDR Then
                    ' set target
                    target_addr = ia
                ElseIf ia.ToString() = LOCAL_OUT_IPADDR Then
                    ' set local
                    local_out_addr = ia
                End If
            Next
            Console.WriteLine()
            Console.WriteLine("target interface address set to {0}", target_addr.ToString())
            Console.WriteLine("local outgoing interface address set to {0}", local_out_addr.ToString())
            If target_addr.ToString() <> TARGET_IPADDR Then
                Console.WriteLine()
                Console.WriteLine("error: target interface not match")
                Console.WriteLine("exit:  interface unavailable")
                Console.ReadKey(True)
                Return
            End If
            If local_out_addr.ToString() <> LOCAL_OUT_IPADDR Then
                Console.WriteLine()
                Console.WriteLine("error: local interface not match")
                Console.WriteLine("exit:  interface unavailable")
                Console.ReadKey(True)
                Return
            End If
            Console.WriteLine("--ok--" & vbLf)
            Console.ForegroundColor = ConsoleColor.Yellow
            Console.WriteLine("ANY KEY TO STOP AND CLOSE ALL" & vbLf)
            Console.ResetColor()
            '#End Region
    
            '#Region "run listeners"
            ' Start new listener for every port in TARGETS_PORT array asynchronously.
            ' An object is needed as a parameter for Thread.
            For i As Integer = 0 To TARGET_PORTS.Length - 1
                Dim o As Object() = New Object() {DirectCast(target_addr, Object), DirectCast(local_out_addr, Object), DirectCast(TARGET_PORTS(i), Object), DirectCast(i, Object)}
                Dim t As New Thread(New ParameterizedThreadStart(AddressOf RunListenerThread))
                t.Start(o)
            Next
            '#End Region
    
            '#Region "close all and exit"
            Console.ReadKey(True)
            Console.WriteLine()
            Try
                Console.WriteLine("closing listeners..")
                For Each l As TcpListener In listeners
                    l.[Stop]()
                Next
                Console.WriteLine("closing sockets..")
                For Each s As SocketStateObj In sockets
                    s.in_socket.Close()
                    s.out_socket.Close()
                Next
            Catch generatedExceptionName As Exception
            End Try
            Console.WriteLine("--ok--")
            Console.ReadKey(True)
            '#End Region
        End Sub
            Public Const PACKET_BUFFSIZE As Integer = 2048
            ' packet buffer in bytes
            Private Const LOCAL_OUT_IPADDR As String = "192.168.1.88"
            ' active localhost external address (set your one)
        Private Const TARGET_IPADDR As String = "138.197.83.21"
            ' destination address (google.com)
            '8080
        Private ReadOnly TARGET_PORTS As Integer() = New Integer() {8080}
    
            Public packet_no As Integer = 0
            ' packet counter
            Private listeners As New ArrayList()
            ' array of references to all listeners
            Private sockets As New ArrayList()
    
    
            Private Sub RunListenerThread(o As Object)
                Dim oa As Object() = DirectCast(o, Object())
                Dim listNo As Integer = CInt(oa(3))
                Try
                    RunListener(DirectCast(oa(0), IPAddress), DirectCast(oa(1), IPAddress), CInt(oa(2)), listNo)
                Catch generatedExceptionName As ThreadAbortException
                    ' <-- listener exception handling code -->
    
                    'Console.WriteLine("listener {0} exception: {1}", listNo, ex.Message);
                Catch ex As Exception
                End Try
            End Sub
    
    
            Private Sub RunListener(listenerInterface As IPAddress, outgoingInterface As IPAddress, listenerPort As Integer, listNo As Integer)
                Dim listener As New TcpListener(listenerInterface, listenerPort)
                listeners.Add(listener)
                listener.Start()
                Console.WriteLine("listener {0} started at {1}:{2}", listNo, listenerInterface.ToString(), listenerPort)
    
                While True
                    Console.WriteLine("listener {0} is waiting for a new client", listNo)
                    Dim incoming_socket As Socket = listener.AcceptSocket()
                    Console.WriteLine("listener {0}: client connected", listNo)
    
                    ' connecting remote host
                    Console.WriteLine("listener {0} is connecting to remote host {1}:{2}", listNo, TARGET_IPADDR, listenerPort)
                    Dim remote_socket As Socket = ConnectSocket(New IPEndPoint(outgoingInterface, 0), TARGET_IPADDR, listenerPort)
                    If remote_socket Is Nothing Then
                        Console.WriteLine("listener {0}: outgoing connection failed", listNo)
                        Continue While
                    End If
                    Console.WriteLine("listener {0}: connected to remote host {1}:{2}", listNo, TARGET_IPADDR, listenerPort)
    
                    ' begin receive on input
                    Dim iso As New SocketStateObj(incoming_socket, remote_socket)
                    sockets.Add(iso)
                    incoming_socket.BeginReceive(iso.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), iso)
    
                    ' begin receive on output
                    Dim oso As New SocketStateObj(remote_socket, incoming_socket)
                    sockets.Add(oso)
                    remote_socket.BeginReceive(oso.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), oso)
                End While
            End Sub
    
    
            Private Sub Read_Callback(ar As IAsyncResult)
                Dim s1 As Socket = Nothing
                Dim s2 As Socket = Nothing
                Try
                    ' retrieve SocketStateObj
                    Dim so As SocketStateObj = DirectCast(ar.AsyncState, SocketStateObj)
                    s1 = so.in_socket
                    s2 = so.out_socket
                    Dim count As Integer = s1.EndReceive(ar)
    
                    If count > 0 Then
                        ' copy of buffer data
                        Dim tmpbuff As Byte() = New Byte(PACKET_BUFFSIZE - 1) {}
                        so.buffer.CopyTo(tmpbuff, 0)
    
                        ' async. wait for next packet
                        s1.BeginReceive(so.buffer, 0, SocketStateObj.BUFF_SIZE, SocketFlags.None, New AsyncCallback(AddressOf Read_Callback), so)
    
                        ' <-- packet filtering -->
    
                        '#Region "show packet info"
                        Console.ForegroundColor = ConsoleColor.Cyan
                        Console.WriteLine("[{0}] packet {1} -> S: {2}  D: {3}  len: {4}", DateTime.Now.ToString("HH:mm:ss"), System.Math.Max(System.Threading.Interlocked.Increment(packet_no), packet_no - 1), s2.LocalEndPoint.ToString(), s1.LocalEndPoint.ToString(), count)
                        Console.ResetColor()
                        '#End Region
    
                        ' send packet to destination (if not filtered)
    
                        ' <-- packet injection or re-sending -->
                        s2.Send(tmpbuff, 0, count, SocketFlags.None)
                    Else
                        ' close connections if packet has empty data                    
                        Console.WriteLine("connection {0} <-> {1} closed", s2.LocalEndPoint.ToString(), s1.LocalEndPoint.ToString())
                        s1.Close()
                        s2.Close()
                    End If
                Catch ex As Exception
                    ' <-- socket exception handling code -->
    
                    'Console.WriteLine("Read_Callback exception: {0}", ex.Message);
                    Try
                        s1.Close()
                        s2.Close()
                    Catch generatedExceptionName As Exception
                    End Try
                End Try
            End Sub
    
    
    
            Private Function ConnectSocket(localEndpoint As IPEndPoint, remoteServer As String, remotePort As Integer) As Socket
                Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                s.Bind(localEndpoint)
                s.Connect(remoteServer, remotePort)
                Return s
            End Function
    
    
    
       
        ''' <summary>
        ''' State object class for AsyncCallback delegation
        ''' </summary>
    
        Public Class SocketStateObj
            Public Shared ReadOnly BUFF_SIZE As Integer = Module1.PACKET_BUFFSIZE
            Public in_socket As Socket = Nothing
            Public out_socket As Socket = Nothing
            Public buffer As Byte() = New Byte(BUFF_SIZE - 1) {}
    
            Public Sub New(in_socket As Socket)
                Me.in_socket = in_socket
            End Sub
    
            Public Sub New(in_socket As Socket, out_socket As Socket)
                Me.in_socket = in_socket
                Me.out_socket = out_socket
            End Sub
        End Class
    
    
    End Module
    

    Wednesday, September 6, 2017 10:33 PM
  • Hi,

    Do you debug your code? After I debug your code,  I found “target_addr” never equal  "93.188.161.129" , the code always return at below line , so, is the problem here?

    If target_addr.ToString() <> TARGET_IPADDR Then
    	Console.WriteLine()
    	Console.WriteLine("error: target interface not match")
    	Console.WriteLine("exit:  interface unavailable")
    	Console.ReadKey(True)
    	Return
    End If
    
    

    Bob


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, September 12, 2017 9:28 AM