Get socket address in C#

The System.Net SocketAddress provides a socket address stored in a System.Byte array. A socket address consists of a member of the System.Net.Sockets.AddressFamily enumeration stored in the first two bytes of the array.

using System;
using System.Net;
using System.Net.Sockets;
public class SocketAddressSample
{
    public static void Main()
    {
        SocketAddress sktaddr1 = new
        SocketAddress(AddressFamily.InterNetwork);
        SocketAddress sktaddr2 = new
        SocketAddress(AddressFamily.InterNetwork, 255);
        Console.WriteLine("SocketAddress.Family = '{0}'",
        sktaddr1.Family);
        Console.WriteLine("SocketAddress.Size = {0}",
        sktaddr1.Size);
        Console.WriteLine("SocketAddress = '{0}'",
        sktaddr1);
        Console.WriteLine("SocketAddress(AddressFamily.InterNetwork) "
        + "== SocketAddress(AddressFamily.InterNetwork, 255) ? = {0}",
        sktaddr1.Equals(sktaddr2));
        Console.WriteLine();
        Console.WriteLine();
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
    }
}

Output:

SocketAddress.Family = ‘InterNetwork’
SocketAddress.Size = 32
SocketAddress = ‘InterNetwork:32:{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}’
SocketAddress(AddressFamily.InterNetwork) == SocketAddress(AddressFamily.InterNetwork, 255) ? = False
Press Enter to continue

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.