Found the problem, the client should send with port = 0 [
ServerEp
] and it will receive a response on the correct port of the server (if you set the client port send to be = the server's port [
ServerEp
] it will always work regardless which is not what you want).
The correct code is below:
private string DoUDPSearch(int port)
{
var host = Dns.GetHostEntry(Dns.GetHostName());
string ipaddr = "";
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
try
{
var ServerEp = new IPEndPoint(ip, 0);
var Client = new UdpClient(ServerEp);
Client.Client.SendTimeout = 2000;
Client.Client.ReceiveTimeout = 2000;
var RequestData = Encoding.ASCII.GetBytes("SomeRequestData");
Client.Send(RequestData, RequestData.Length, new IPEndPoint(IPAddress.Broadcast, port));
var ServerResponseData = Client.Receive(ref ServerEp);
var ServerResponse = Encoding.ASCII.GetString(ServerResponseData);
ipaddr = ServerEp.Address.ToString();
logger("Server IP = " + ServerEp.Address);
Client.Close();
return ipaddr;
}
catch { Console.WriteLine("unable to connect."); }
}
}
logger("Server IP not found.");
return ipaddr;
}