Solved

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

Posted on 2008-10-20
10
807 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:godwindotnet
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Thanks though for attempting and taking the time to help me.
Cheers!!
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
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.

771 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

11 Experts available now in Live!

Get 1:1 Help Now