Click here to Skip to main content
15,886,578 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Receive IPV6 or IPV4 based Data Using C#

Rate me:
Please Sign up or sign in to vote.
4.80/5 (6 votes)
27 Apr 2014CPOL2 min read 21.3K   683   12   3
Receive IPV6 or IPV4 based data using TcpListener

Introduction

IPV6 means Internet Protocol Version 6. This is the latest communication protocol that provides identification and location for computer or devices on network and routes traffic across internet.

IPV4 means Internet Protocol Version 4. This is most successful using protocol on network.

Example for IPV6 Address is fe80:cft7:b16:2817:b24a:1dd7

Example for IPV4 Address is xxx.xxx.xxx.47

Background

First, I wrote code to receive IPv4 data using TCPListener. We found one issue that our code was not able to pick IPv6 data. Then I did a small R&D and found that to receive IPv6 we have to use TCPListener with address type IPV6.

IPV6 vs IPV4

IPV4 address is a 32 bit numeric address written in decimal and four numbers separated by dot.
For example: 1.67.87.33

IPV6 address is a 128 bit written in hexadecimal and separated by colon.
For example: fe80:cft7:b16:2817:b24a:1dd7

To know more about IPV6 and IPV4, please refer to IPv6 vs IPv4.

Using the Code

I have used System.Net.Sockets.TcpListener for receiving data. Here, TCP listener is monitoring to the 95 port. Thread is used to pick data in Asynchronous manner.

C++
int portno = 95

      tcplistIpv6 = new TcpListener(IPAddress.IPv6Any, portno);
      tcplistIPV4 = new TcpListener(IPAddress.Any, portno);
      listenThread = new Thread(new ThreadStart(listeningToclients));
      listenThread.Start();

Next, expose a method namely listeningToclients. Below is the sample code to start TCP Listener and monitor the port for IPV6 /IPvV 4 data.

C++
//listener
       public void listeningToclients()
       {
           try
           {
               tcplistIpv6.Start();
               tcplistIPV4.Start();

               Console.WriteLine("Server started!");
               Console.WriteLine("Waiting for clients data ...");

               while (true)
               {
                   if (!tcplistIpv6.Pending())
                   {
                       Thread.Sleep(500);
                   }
                   else
                   {
                       TcpClient tcpClient = tcplistIpv6.AcceptTcpClient();
                       Thread clientThread = new Thread(new ParameterizedThreadStart(handleClient));
                       clientThread.Start(tcpClient);
                   }

                   if (!tcplistIPV4.Pending())
                   {
                       Thread.Sleep(500);
                   }
                   else
                   {
                       TcpClient tcpClient = tcplistIPV4.AcceptTcpClient();
                       Thread clientThread = new Thread(new ParameterizedThreadStart(handleClient));
                       clientThread.Start(tcpClient);
                   }
               }
           }
           catch (Exception ex)
           {
               Console.WriteLine("exception in listeningToclients : " + ex.Message);
           }

       }

while (true) where "while(true)" used for continuously monitoring the port. TCP Listener provides a method called Pending. This method is used to determine any pending connection requests that are available or not. If no request is available, I am making thread sleep for 500 milliseconds.

If request is available, then accept the TCP Client and receive the data from request. Using TCPListener.AccetpTcpClient(), we can accept the client request. For data receiving from request, I used the following code.

C++
//client handler
        public void handleClient(object clientObj)
        {
            try
            {
                TcpClient client = (TcpClient)clientObj;
               
                NetworkStream stream = client.GetStream();

                Console.WriteLine("****************************************************");               

                using (StreamReader reader = new StreamReader(stream))
                {
                   
                    string inputStreamStr = reader.ReadToEnd().ToString();
                    Console.WriteLine("Data : " + inputStreamStr);
                    AddressFamily InterNetwork = client.Client.LocalEndPoint.AddressFamily;
                    string strIptYpe = client.Client.RemoteEndPoint.ToString();
                    if (InterNetwork.ToString().ToLower().Contains("v6"))
                    {
                        strIptYpe = strIptYpe + " - ipv6 Address.";
                    }
                    else
                    {
                        strIptYpe = strIptYpe + " - ipv4 Address.";
                    }
                    Console.WriteLine("data sent thru  : " + strIptYpe);
                }             
            }
            catch (Exception exe)
            {
                Console.WriteLine("Exception in handleClient " + exe.Message);
            }
        } 

handleClient

This method is mainly used to convert received data /stream into string format in Asynchronous manner.

Sample Output

Image 1

The second message is sent through IPV6 based address. To know more about IPV6 and IPV4, please refer to the following links:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 4 Pin
LostTheMarbles27-Apr-14 23:46
professionalLostTheMarbles27-Apr-14 23:46 
GeneralRe: My vote of 4 Pin
munagalasantosh28-Apr-14 0:30
munagalasantosh28-Apr-14 0:30 
GeneralRe: My vote of 4 Pin
LostTheMarbles28-Apr-14 0:41
professionalLostTheMarbles28-Apr-14 0:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.