crazyTech
crazyTech

Reputation: 1477

How to implement instantiation of TcpClient, IPEndPoint , IPAddress objects instantiating for both cases IPv4 and IPv6 address when passed As Strings

For my .NET C# application, we have modules that are need to communicate via the TCP/IP protocol.

I decided to use Microsoft's System.Net.Sockets API

The modules that are represented by the "TcpListener" class could be either be

-IPv4 address based -IPv6 address based

The problem is that the modules that use the "TcpClient" class need to instantiate the "TcpClient" in such a way that it is intelligent to take either IPv4 or IPv6 address (that initially gets passed as a string)

To elaborate, the module that uses "TcpClient" class could have a constructor like the following:

public ClientModule(string ipV4OrIpV6Address, int portNumber){
………………………
…………..
……….
}

When I reviewed Microsoft's documentation ( https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.-ctor?view=netframework-4.8#System_Net_Sockets_TcpClient__ctor_System_Net_IPEndPoint_ ) , I found the following TcpClient constructor:

TcpClient(IPEndPoint)

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

Furthermore, I tried to search more about instantiating the IPEndPoint class, and I came across ( https://learn.microsoft.com/en-us/dotnet/api/system.net.ipendpoint.-ctor?view=netframework-4.8#System_Net_IPEndPoint__ctor_System_Net_IPAddress_System_Int32_ )

Each of the modules will be on different physical computer servers.

How do I go about instantiating the Microsoft's IPAddress object in such a way that it will be intelligent enough to handle both IPv4 and IPv6 address As Strings regardless of which one gets passed as an argument?

Upvotes: 1

Views: 1911

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70652

The TcpClient(string, int) constructor ultimately winds up calling IPAddress.TryParse(string) on the string value you pass in, and it will attempt to apply the result to both an IPv4 and IPv6 socket.

So, you should not have to do anything special. Just pass the IP address to the TcpClient(string, int) constructor and let the TcpClient class deal with it (well, actually the Dns class ultimately is what does the address resolution). There should be no need to do any explicit work to handle IPv6 addresses. Parsing the address yourself is just a waste of code and time.

Upvotes: 2

user10316640
user10316640

Reputation:

Use IPAddress.Parse(string ipAddress) to build the endpoint.

It accepts a string containg either an IPv4 dotted decimal notation or IPv6 Colon separated address string, and returns an System.Net.IPAddress.

public void ClientModule(string ipV4OrIpV6Address, int portNumber)
{
   IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipV4OrIpV6Address), int port); 
TcpClient client = new TcpClient(endpoint);
// Do something with the client
}

Upvotes: 4

Related Questions