Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 862
  • Last Modified:

PORT FORWARDING (doing the same thing what router does through software)

Hello everyone,
I need some help in developing an application which simply listens on a specific port and forwards alllll the incoming requests to another pc on the same port.


Its basically EXACTLY the same thing a router does when we configure PORT FORWARDING. I want to do this programatically through vb.net or c#.
I've found some code here...
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_23276633.html

but...it's not yet complete...
I would be grateful if someone could help me with this...
Thanks
0
godwindotnet
Asked:
godwindotnet
  • 6
  • 4
1 Solution
 
MatthiasVanceCommented:
You would need to set up a socket which connects to another port on the same machine, and transmit all data you are receiving from the source port.

Kind regards,

Matthias Vance
0
 
godwindotnetAuthor Commented:
yes...but how do I do it?
It would be great if you could give me some code snipplet to get me started.
Thanks
0
 
MatthiasVanceCommented:
Assuming you have the other side of the code ready, you need to create a socket and connect it when a client connects to *your* program. If you receive any data, it should be send to the other service. I provided some example code, and I'm assuming here that you receive a byte array.

Kind regards,

Matthias Vance
' Create a socket
Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
 
' Connect to the other service running on another port
s.Connect("www.google.com", 80)
 
' Send data
s.Send(data, data.Length, SocketFlags.None)

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
godwindotnetAuthor Commented:
Thats great...
Now I think,the packets received from this port is forwarded to the other port on the other PC.
But,no response is coming back :-(
Please help me with this..
Thanks..
0
 
MatthiasVanceCommented:
I suggest you take a look at asynchronous socket functions, because I don't think you can make your application work in a linear way. Note that that is a more advanced subject.

If your application works in a linear way, it will block while it's waiting from data from either side.

Kind regards,

Matthias Vance
' Code to receive
Dim buffer(1024) as Byte
s.Receive(buffer, 0, buffer.length, SocketFlags.None)

Open in new window

0
 
godwindotnetAuthor Commented:
nope,it doesn't work :-(

i've attached the complete code of what I've tried by combining what you gave me along with what I found here...
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_23276633.html

I'm really not sure what is the problem now....and why its not working...


'CLASS CODE
Imports System.Net.Sockets
Imports System.Text
 
 
 
 
' The UserConnection class encapsulates the functionality of a TcpClient connection with streaming for a single user.
Public Class modul_UserConnection
    Const READ_BUFFER_SIZE As Integer = 255
 
    ' Overload the New operator to set up a read thread.
    Public Sub New(ByVal client As TcpClient)
        Me.client = client
        ' This starts the asynchronous read thread.  The data will be saved into readBuffer.
        Me.client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf StreamReceiver, Nothing)
    End Sub
 
    Private client As TcpClient
    Private readBuffer(READ_BUFFER_SIZE) As Byte
    Private strName As String
 
    ' The Name property uniquely identifies the user connection.
    Public Property Name() As String
        Get
            Return strName
        End Get
        Set(ByVal Value As String)
            strName = Value
        End Set
    End Property
 
 
    Public Event LineReceived(ByVal sender As modul_UserConnection, ByVal Data As String)
 
    ' This subroutine uses a StreamWriter to send a message to the user.
    Public Sub SendData(ByVal Data As String)
        ' Synclock ensure that no other threads try to use the stream at the same time.
        SyncLock client.GetStream
            Dim writer As New IO.StreamWriter(client.GetStream)
            writer.Write(Data & Chr(13) & Chr(10))
            ' Make sure all data is sent now.
            writer.Flush()
        End SyncLock
    End Sub
 
    ' This is the callback function for TcpClient.GetStream.Begin. It begins an
    ' asynchronous read from a stream.
    Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
 
    Private Sub StreamReceiver(ByVal ar As IAsyncResult)
        Dim BytesRead As Integer
        Dim strMessage As String
 
 
        ' Ensure that no other threads try to use the stream at the same time.
        SyncLock client.GetStream
            ' Finish asynchronous read into readBuffer and get number of bytes read.
            BytesRead = client.GetStream.EndRead(ar)
        End SyncLock
 
        ' Convert the byte array the message was saved into, minus one for the
        ' Chr(13).
        strMessage = Encoding.ASCII.GetString(readBuffer, 0, BytesRead - 1)
        RaiseEvent LineReceived(Me, strMessage)
 
        ' Ensure that no other threads try to use the stream at the same time.
        SyncLock client.GetStream
            ' Start a new asynchronous read into readBuffer.
            client.GetStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE, AddressOf StreamReceiver, Nothing)
 
        End SyncLock
        s.Connect("10.0.3.11", 8080)
        s.Send(readBuffer, READ_BUFFER_SIZE, SocketFlags.None)
        Dim buffer(1024) As Byte
        s.Receive(buffer, 0, buffer.Length, SocketFlags.None)
    End Sub
 
End Class
 
 
 
 
 
 
 
=============================================================
 
 
 
 
 
 
 
'FORM CODE
 
 
Imports System.Net.Sockets
Imports WindowsApplication1
 
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        listenerThread = New Threading.Thread(AddressOf DoListen)
        listenerThread.Start()
    End Sub
    Dim PORT_NUM As Integer = 8080
    Dim listener As TcpListener
    Dim listenerThread As Threading.Thread
    '//On formLoad type...
       
 
    '// add these subs in your form
    ''' <summary>
    ''' This subroutine is used as a background listener thread to
    ''' allow reading incoming messages without lagging the user interface.
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DoListen()
 
        ' Listen for new connections.
        listener = New TcpListener(System.Net.IPAddress.Any, PORT_NUM)
        listener.Start()
        Do
            'Create a new user connection using TcpClient returned by TcpListener.AcceptTcpClient()
            Dim client As New modul_UserConnection(listener.AcceptTcpClient)
 
            'Create an event handler to allow the UserConnection to communicate with the window.
            AddHandler client.LineReceived, AddressOf OnLineReceived
        Loop Until False
 
    End Sub
    
    ''' <summary>
    ''' _______This is the event handler for the UserConnection when it receives a full line._________
    ''' Parse the command and parameters and take appropriate action.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="data"></param>
    ''' <remarks></remarks>
    Private Sub OnLineReceived(ByVal sender As modul_UserConnection, ByVal data As String)
 
        'Stop
 
 
        Console.WriteLine(data)
 
    End Sub
End Class

Open in new window

0
 
godwindotnetAuthor Commented:
This application here does port forwarding .........BUT,its not open source and not made in C#. :-(
http://www.brooksyounce.com/soft/spf.htm


I don't require all those filter options which it has. I only need the PORT FORWARDING part.
Please help me.
Thanks.

0
 
godwindotnetAuthor Commented:
Nevermind,I got the solution about doing it from here.....
http://blog.mike-obrien.net/PermaLink,guid,1e7ccfad-5cb2-48a9-8dc1-e25da2663840.aspx

Works just as expected
0
 
MatthiasVanceCommented:
Okay, good to hear that you found a solution! Now please accept your own post as the solution and assign any points to posts that might have assisted you.

Kind regards,

Matthias Vance
0
 
godwindotnetAuthor Commented:
Thanks though for attempting and taking the time to help me.
Cheers!!
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now