Solved

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

Posted on 2008-10-20
10
815 Views
Last Modified: 2013-12-17
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
Comment
Question by:godwindotnet
  • 6
  • 4
10 Comments
 
LVL 8

Expert Comment

by:MatthiasVance
ID: 22765163
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
 

Author Comment

by:godwindotnet
ID: 22765358
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
 
LVL 8

Expert Comment

by:MatthiasVance
ID: 22765449
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
 

Author Comment

by:godwindotnet
ID: 22766215
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
 
LVL 8

Expert Comment

by:MatthiasVance
ID: 22766239
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:godwindotnet
ID: 22766342
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
 

Author Comment

by:godwindotnet
ID: 22766433
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
 

Author Comment

by:godwindotnet
ID: 22770802
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
 
LVL 8

Accepted Solution

by:
MatthiasVance earned 500 total points
ID: 22770878
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
 

Author Closing Comment

by:godwindotnet
ID: 31508154
Thanks though for attempting and taking the time to help me.
Cheers!!
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now