Christopher Tarquini
Christopher Tarquini

Reputation: 11332

C# server that supports IPv6 and IPv4 on the same port

Is it possible to have a Socket that listens and accepts both IPv6 and IPv4 clients? I used a IPv6 socket in C# hoping that it would automatically be backwards compatible but IPv4 clients cause an invalid ip address exception.

Upvotes: 6

Views: 15443

Answers (3)

Chronial
Chronial

Reputation: 70663

Using TcpListener:

var listener = new TcpListener(IPAddress.IPv6Any, myport)
listener.Server.DualMode = true
listener.Start()

Note: Internally this is the exactly the same as Matumba's answer.

Upvotes: 1

Matthew Iselin
Matthew Iselin

Reputation: 10670

Have a look here. You can accept IPv4 clients as well as IPv6 clients with the one server socket.

Upvotes: 7

Matumba
Matumba

Reputation: 328

Set the socket's IPv6Only option to false:

Socket MySocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
MySocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

(taken from Matthew Iselin's second link)

Upvotes: 9

Related Questions