Socket Programming

phicha

Well-known member
Joined
May 11, 2009
Messages
45
Programming Experience
Beginner
how to make this source code work ? some how i need it.
i know it's c# code, and i am so sorry.
but somehow i need help.

VB.NET:
=== PROGRAM START ===
using System;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

class PortForwardingService {
// initially as an EXE, this will be converted to a service app

public static void Main(string[] args) {
      PFS pfs = new PFS(args);
}
}
class PFS {

      public PFS(){;}

public PFS(string[] args) {

      IPAddress hostIP;
      int listenPort;
      int sendPort;

      //read data from configuration file
      if (args.Length == 0) { //this is the default config file
            hostIP = IPAddress.Parse(ConfigurationSettings.AppSettings["hostIP"]);
            listenPort = Convert.ToInt32(ConfigurationSettings.AppSettings["listenPort"]);
            sendPort = Convert.ToInt32(ConfigurationSettings.AppSettings["sendPort"]);
            Console.WriteLine("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort);
            
      } else {
            if (args.Length == 1) { //this is the config file name provided, at the moment, not implemented
                  hostIP = IPAddress.Parse(ConfigurationSettings.AppSettings["hostIP"]);
                  listenPort = Convert.ToInt32(ConfigurationSettings.AppSettings["listenPort"]);
                  sendPort = Convert.ToInt32(ConfigurationSettings.AppSettings["sendPort"]);
                  Console.Write("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort);
            } else {
                  if (args.Length == 3) {//instead of a config file, arguments are provided
                        hostIP = IPAddress.Parse(args[0]);
                        listenPort = Convert.ToInt32(args[1]);
                        sendPort = Convert.ToInt32(args[2]);
                        Console.Write("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort);
                  } else { //incorrect number of arguments
                        Console.WriteLine ("Error: Incorrect number of arguments.\n" +
                        "Usage: PortForwardingService <IP address> <Listen Port> <Send Port>\nor\n"+
                                  "PortForwardingService <configuration file>\n"+
                              "Either provide a configuration file, or an IP address and the ports to read from and forward to.");
                        return;
                  }
            }
      }

      //see if we can bind to the given IP and port
    // create the socket
    Socket listenSocket = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream,
                                     ProtocolType.Tcp);
    //server socket options
    listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

    IPEndPoint ep = new IPEndPoint(hostIP, listenPort);
    try {
          listenSocket.Bind(ep);
    } catch (SocketException se) {
      Console.Write ("SocketException Error: {0}", se.Message);
      return;
    } catch (Exception e) {
      Console.Write ("Error: {0}", e.Message);
      return;
    }

    int backlog = 1; //int backlog = (int)SocketOptionName.MaxConnections;
    // start listening
    listenSocket.Listen(backlog);

    Socket acceptSocket, responseSocket;

    Console.WriteLine ("Successfully listening to port {0} on {1}", listenPort, hostIP);            

    //create the Socket to which we're redirecting
    Socket sendSocket = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream,
                                     ProtocolType.Tcp);
    //Send operations will timeout of confirmation is not received within 10000 milliseconds
    sendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000);

    ep = new IPEndPoint(hostIP, sendPort);     //redefined
    try {
          sendSocket.Connect(ep);  //bind is not necessary, we're assuming there's a service running at sendPort
    } catch (SocketException se) {
      Console.Write ("SocketException Error: {0}", se.Message);
      return;
    } catch (Exception e) {
      Console.Write ("Error: {0}", e.Message);
      return;
    }

    if (! sendSocket.Connected) {
      Console.WriteLine("connection fails");
        return;
    } else {
      Console.WriteLine ("Successfully connected to port {0} on {1}", sendPort, hostIP);            
    }


    //loop to transfer data packets
    int k=0;
    int sz = 256, received=0;
    byte[] sendData = new byte[sz];

    while (true) {
      //accept socket
      acceptSocket = listenSocket.Accept();
//      responseSocket = sendSocket.Accept();
      
      //receive data from one port and send it to the next
        while ((received = acceptSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0) {
         sendSocket.Send(sendData, sendData.Length, SocketFlags.None);
        }
/*        //receive response and return it to the originator
        while ((received = responseSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0) {
         acceptSocket.Send(sendData, sendData.Length, SocketFlags.None);
        } */

      
      //if(System.Environment.Version.Major < 2) {
      #if FRAMEWORK_VERSION_2
            k = Console.ReadKey();
      #else
            k = Console.Read();
      #endif
      if (k == 81 || k == 113) {
            Console.Write ("Quitting...");
            //listenSocket.Shutdown(SocketShutdown.Receive); //you don't do graceful shutdown on listening socket but close it
            sendSocket.Shutdown(SocketShutdown.Both);
            listenSocket.Close();
            sendSocket.Close();
            return;
      }
    }

}
}
=== PROGRAM END  ===

=== CONFIG FILE START ===
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="hostIP" value="127.0.0.1" />
        <add key="listenPort" value="80" />
        <add key="sendPort" value="5225" />
      <!-- keys to do for version 2 implementation -->
        <!-- add key="targetIP" value="127.0.0.1" /-->
        <!-- add key="debugMode" value="true" /-->
    </appSettings>
</configuration>
=== CONFIG FILE END ===

Thanks,
 
Thanks sir, I Convert it to VB Dot net.

This code used to receive and forward socket data. but somehow it not worked when retrive data and send back to sender.

thanks,

Module1.vb
VB.NET:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Configuration
Class PortForwardingService

    ' initially as an EXE, this will be converted to a service app
    Public Shared Sub Main(ByVal args() As String)
        Dim pfs As PFS = New PFS(args)
        Console.ReadKey()
    End Sub
End Class
Class PFS

    Public Sub New()
        MyBase.New()

    End Sub

    Public Sub New(ByVal args() As String)
        MyBase.New()
        Dim hostIP As IPAddress
        Dim listenPort As Integer
        Dim sendPort As Integer
        'read data from configuration file
        If (args.Length = 0) Then
            'this is the default config file
            hostIP = IPAddress.Parse(ConfigurationSettings.AppSettings("hostIP"))
            listenPort = Convert.ToInt32(ConfigurationSettings.AppSettings("listenPort"))
            sendPort = Convert.ToInt32(ConfigurationSettings.AppSettings("sendPort"))
            Console.WriteLine("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort)
        ElseIf (args.Length = 1) Then
            'this is the config file name provided, at the moment, not implemented
            hostIP = IPAddress.Parse(ConfigurationSettings.AppSettings("hostIP"))
            listenPort = Convert.ToInt32(ConfigurationSettings.AppSettings("listenPort"))
            sendPort = Convert.ToInt32(ConfigurationSettings.AppSettings("sendPort"))
            Console.Write("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort)
        ElseIf (args.Length = 3) Then
            'instead of a config file, arguments are provided
            hostIP = IPAddress.Parse(args(0))
            listenPort = Convert.ToInt32(args(1))
            sendPort = Convert.ToInt32(args(2))
            Console.Write("IP address: {0}  Port1: {1}  Port2: {2}", hostIP, listenPort, sendPort)
        Else
            'incorrect number of arguments
            Console.WriteLine(("Error: Incorrect number of arguments." & vbLf + ("Usage: PortForwardingService <IP address> <Listen Port> <Send Port>" & vbLf & "or" & vbLf + ("PortForwardingService <configuration file>" & vbLf + "Either provide a configuration file, or an IP address and the ports to read from and forward to."))))
            Return
        End If
        'see if we can bind to the given IP and port
        ' create the socket
        Dim listenSocket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        'server socket options
        listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1)
        Dim ep As IPEndPoint = New IPEndPoint(hostIP, listenPort)
        Try
            listenSocket.Bind(ep)
        Catch se As SocketException
            Console.Write("SocketException Error: {0}", se.Message)
            Return
        Catch e As Exception
            Console.Write("Error: {0}", e.Message)
            Return
        End Try
        Dim backlog As Integer = 1
        'int backlog = (int)SocketOptionName.MaxConnections;
        ' start listening
        listenSocket.Listen(backlog)
        Dim responseSocket As Socket
        Dim acceptSocket As Socket
        Console.WriteLine("Successfully listening to port {0} on {1}", listenPort, hostIP)
        'create the Socket to which we're redirecting
        Dim sendSocket As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        'Send operations will timeout of confirmation is not received within 10000 milliseconds
        sendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000)
        ep = New IPEndPoint(hostIP, sendPort)
        'redefined
        Try
            sendSocket.Connect(ep)
            'bind is not necessary, we're assuming there's a service running at sendPort
        Catch se As SocketException
            Console.Write("SocketException Error: {0}", se.Message)
            Return
        Catch e As Exception
            Console.Write("Error: {0}", e.Message)
            Return
        End Try
        If Not sendSocket.Connected Then
            Console.WriteLine("connection fails")
            Return
        Else
            Console.WriteLine("Successfully connected to port {0} on {1}", sendPort, hostIP)
        End If
        'loop to transfer data packets
        Dim k As Integer = 0
        Dim received As Integer = 0
        Dim sz As Integer = 256
        Dim sendData() As Byte = New Byte((sz) - 1) {}

        While True
            acceptSocket = listenSocket.Accept()
            While (received = acceptSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0
                sendSocket.Send(sendData, sendData.Length, SocketFlags.None)
            End While

            'responseSocket = sendSocket.Accept()
            While (received = sendSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0
                acceptSocket.Send(sendData, sendData.Length, SocketFlags.None)
            End While


        End While

        '        while (true) {
        '      //accept socket
        '      acceptSocket = listenSocket.Accept();
        '//      responseSocket = sendSocket.Accept();

        '      //receive data from one port and send it to the next
        '        while ((received = acceptSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0) {
        '         sendSocket.Send(sendData, sendData.Length, SocketFlags.None);
        '        }
        '/*        //receive response and return it to the originator
        '        while ((received = responseSocket.Receive(sendData, 0, sendData.Length, SocketFlags.None)) > 0) {
        '         acceptSocket.Send(sendData, sendData.Length, SocketFlags.None);
        '        } */


        '      //if(System.Environment.Version.Major < 2) {
        '#If FRAMEWORK_VERSION_2 Then
        '            k = Console.ReadKey();
        '#Else
        '            k = Console.Read();
        '#End If
        '      if (k == 81 || k == 113) {
        '            Console.Write ("Quitting...");
        '            //listenSocket.Shutdown(SocketShutdown.Receive); //you don't do graceful shutdown on listening socket but close it
        '            sendSocket.Shutdown(SocketShutdown.Both);
        '            listenSocket.Close();
        '            sendSocket.Close();
        '            return;
        '      }
        '    }


    End Sub
End Class

app.config
VB.NET:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="hostIP" value="127.0.0.1" />
    <add key="listenPort" value="8080" />
    <add key="sendPort" value="1433" />
    <!-- keys to do for version 2 implementation -->
    <!-- add key="targetIP" value="127.0.0.1" /-->
    <!-- add key="debugMode" value="true" /-->
  </appSettings>
</configuration>
 
Back
Top