Government Security
Network Security Resources

Jump to content


Sockets In .net

- - - - - windows network dns .net
  • Please log in to reply
No replies to this topic

#1 wiNGCom


    Private First Class

  • Members
  • 33 posts

Posted 19 July 2005 - 11:20 AM

I found this faq on that seemed usefull for people who want to use sockets in .NET I do not take credit for this document since it was made by WWJD from But it seemed appropriate to post it here. Easier way to use sockets, of course with limitations, ideal for beginning programmers.

url: hxxp://

This FAQ introduces the Microsoft.Net® Framework’s Socket class. It demonstrates how to use a Socket object to send and receive some data. The Socket class makes it possible for you to write applications that can connect to other computers through a network, be it a local area network or the internet.

Why should you be interested in learning about the Socket class? Have you considered creating a chat application, a multi-player internet game, or a secure channel for your company’s data? These are a few of the reasons for learning how to program with the Socket class.

Language : Visual Basic.Net/Visual Studio.Net 2002
Framework : .Net Framework version 1 or 1.1
Imports :

Network Protocol– A formal set of rules which governs how data is transmitted across a network. There are many network protocols.

TCP/IP – Two protocols from the suite of network protocols on which all internet communication is based.

Berkeley Sockets - A specific implementation of TCP/IP.

Winsock – The Windows OS implementation of Berkeley Sockets.

Socket Class – A .Net Framework class which provides managed access to the Winsock API

Walk Through
The Socket class provides a way for you to add the power of TCP/IP to your application without dealing directly with network protocols, TCP/IP, Berkeley Sockets, Winsock, or the Winsock API.

This walk through shows how to 1) import the System.Net namespaces necessary to implement Sockets; 2) declare Socket, TcpListener, IPEndpoint, and Timer variables; 3) send data with a Socket object; and 4) receive data with a Socket object.

A project created from this walkthrough is attached for reference.

Step One: Import the System.Net namespaces.

Use Visual Studio.Net to create a new Windows application named MySockets. Open the code behind Form1. At the top of the code, above the “Public Class Form1” line, add:

Imports System.Net

NOTE: See the DemoSockets project for examples.

Step Two: Declare Socket, TcpListener, IPEndPoint, and Timer variables.

Add the code that will create the Socket object and other objects required for this walkthrough. After the “Windows Form Designer generated code” region in Form1 add:

Code:Private _ClientSocket As Socket
Private _HostSocket As Socket
Private _TcpListener As New TcpListener(5124)
Private _IpEndPoint As New _
IPEndPoint(Dns.GetHostByName(Dns.GetHostName).AddressList(0), 5124)
Private _Timer As New Timer()

NOTE: See the DemoSockets project for important comments about these statements.

The properties and methods of the Socket object provide an interface to TCP/IP. With them an application can establish a connection, monitor the connection, send/receive data, and close the connection. Learn more: Socket Class

A TcpListner object listens for connections from TCP/IP network clients. Learn more: TcpListener Class

An IPEndPoint object represents a network endpoint as an IP address and a port number. The _IpEndPoint declaration above uses shared methods of the Dns Class to get the internet bound address of the computer:


Learn more: Dns Class

STEP THREE: Send data with a Socket.

The SendButton_Click subroutine in the SocketsDemo project uses the _ClientSocket object to send data to network end point contained in the _IPEndPoint object.

Code:Private Sub SendButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles SendButton.Click
' Instantiate a new Socket object and
' assign a reference to it to the _ClientSocket variable.
' AddressFamily.InterNetwork is an
' address which meets the IP protocol version 4 standard.
' SocketType.Stream supports reliable, two-way,
' connection-based byte streams without the duplication
' of data and without preservation of boundaries.
' ProtocolType.Tcp = Transmission Control Protocol
_ClientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Call the Socket Connection method passing it the IP
' address and port of this computer (_IpEndPoint)
' This establish the Sockets connection to a remote device.
' Convert sendData (string) into a Byte array.
Dim Buffer() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes(ClientMessageTextBox.Text)
' _ClientSocket sends the data to port 5124.
_ClientSocket.Send(Buffer, 0, Buffer.Length, SocketFlags.None)
' Enable _Timer so the CheckListener method will be called every 1 second.
' Set _Timer interval to 1 second.
_Timer.Interval = 1000
' Start the timer.
' Call the Socket Shutdown method passing it the
' SocketShutDown.Both parameter.
' This disables sends and receives on the socket.
' Call the Socket Close method to close the socket.
' Forces a socket connection to close.
End Sub

Here are some key points from concerning the subroutine.

_ClientSocket is assigned a new Socket object.

The _ClientSocket is passed the _IPEndPoint object when its Connect method is called. This opens a connection to an end point on the network.

To send a String through the network it must be converted into a byte array. In the subroutine an ASCIIEncoding object’s GetBytes method is used to convert the text from the ClientMessageTextBox into bytes which are used to fill the Buffer() byte array.

The data is sent using the _ClientSocket’s Send method.

The _Timer object is set/started to raise a Tick event every second.

The _SocketObject’s ShutDown and Close methods must be called after the data has been sent.

STEP FOUR: Receive data with a Socket object.

The CheckTcpListener subroutine in the SocketsDemo project uses a Socket object to received data.

Code:Private Sub CheckTcpListener(ByVal sender As Object, ByVal e As System.EventArgs)
' This method is called every second when _Timer is running.

' Check the TcpListner Pending Property
If _TcpListener.Pending = True Then
' TcpListner has pending connection; pass the connection to _HostSocket
' Call the AcceptSocket function on _TcpListner;
' assign the return value (a connection) to _HostSocket.
_HostSocket = _TcpListener.AcceptSocket

' Call the Socket Poll method to determine if the status of _HostSocket
' is SelectRead which means data is available to read.
If _HostSocket.Poll(1, SelectMode.SelectRead) Then
' _HostSocket has data to be read.
' Call the Socket Available method on _HostSocket;
' assign the return value (Bytes available) to an integer variable.
Dim numBytes As Int32 = _HostSocket.Available
' Instantiate an array of Bytes which is the size of the
' number of Bytes available.
Dim Data(numBytes) As Byte
' Call the Socket Receive method.
' Receives data from a connected Socket.
' Convert the Byte array received into a String
HostMessagesReceivedTextBox.Text &= System.Text.ASCIIEncoding.ASCII.GetString(Data)
HostMessagesReceivedTextBox.Text &= ControlChars.CrLf
' Stop _Timer. Message was received and processed.
End If
End If
End Sub

When the _Timer object raises a Tick event the CheckTcpListner subroutine handles the Tick event. Here are some key points from this subroutine.

A TcpListner object must be checked for a pending connection, it does not raise a connection pending event.

A TcpListner object must pass a pending connection to a Socket for further processing so it can go back to listening for connections.

When a Socket object is passed a connection it must be polled to determine the state of the socket. In the DemoSockets project the _HostSocket object is polled for the SelectMode.SelectRead state. The SelectMode.SelectRead state indicates the Socket received data.

The Socket object’s Available property gets the number of bytes of data that has been received from the network – the bytes that are available to be read.

The data must be received into a byte array then converted to characters. At this point encoding is used to convert a array of bytes to characters. In the DemoSockets project the GetString method of an ASCIIEncoding object is used to convert the byte arrray to a String.

IMPORTANT: For simplicty’s sake, error handling was left out of the SocketsDemo. A real-world application should wrap the code that imlements sockets with Try..Finally exception handlers which will close the Socket should and error occur. A socket uses Windows OS resources which should not be left in an open state if an error occurs.

The .Net Framework’s Socket class is your gateway to the TCP/IP world. Add the power of TCP/IP to your applications with Sockets.

This FAQ is has been a small introduction to how to use Sockets. Visit the links provided in the FAQ to learn more

PS: Url has an example project

Also tagged with one or more of these keywords: windows, network, dns, .net