Home > database >  SocketException: The requested address is not valid in the context
SocketException: The requested address is not valid in the context

Time:12-01

I am able to communicate with socketTest with the same ip address, but within UNITY I get an error message

SocketException: The requested address is not valid in the context.

I tried

socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Parse(sHostIpAddress), nPort));

sHostIpAddress is not 127.0.0.1

How to can i fix it?

CodePudding user response:

This is not really specific to Unity but rather c# in general.

Socket.Bind is for binding the socket to a specific local endpoint! Such as for example you want to limit the socket to a specific local network adapter / address (by default it will use any/all) or a specific local port (by default it will pick any free local port)

Use the Bind method if you need to use a specific local endpoint. You must call Bind before you can call the Listen method. You do not need to call Bind before using the Connect method unless you need to use a specific local endpoint.

Usually you use Bind mostly for the server side for listening and waiting for incoming connections or for connectionless protocols like UDP.

You most probably simply want to rather use Socket.Connect for establishing a connection to a remote server.

When using Connect without Bind then it will simply pick the network adapter / address it finds to be the best fit for reaching the given host address and picks the next free local port.


However, in general I would recommend to rather use TcpClient instead of composing and configuring the Socket "manually" (except the use case requires it).

var tcpClient = new TcpClient(sHostIpAddress, nPort);

This constructor will automatically start a connection attempt. TcpClient is an IDisposable and cleans up the underlying socket, stream etc when it is disposed. It also is (in my eyes) way easier to configure and to sent and receive data with it.

  • Related