I am a beginner myself, so please take my answer with caution, as it might be wrong.
But since noone answered, i will try to help you, but i am not sure if i even understood your question.
Instead of using localhost, you maybe should try to get the active network adapter.
Something like this maybe:
public static IPAddress GetLocalIPAddress()
{
IPAddress? myAddress;
foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (networkInterface.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in networkInterface.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip.Address))
{
myAddress = ip.Address;
var Endpoint = new IPEndPoint(myAddress, PORT);
if (CheckConnection(Endpoint))
return myAddress;
}
}
}
}
return null;
}
For port you can use a fixed port number if you have one, or 0 which should mean any.
For the CheckConnection you could try to connect to the google servers, which should be always availible.
public static bool CheckConnection(IPEndPoint theEndpoint)
{
if (theEndpoint.Address == null || theEndpoint.Port == 0)
{
return false;
}
IPAddress ipAddress = theEndpoint.Address;
int port = theEndpoint.Port;
if (ipAddress.ToString() == "0.0.0.0")
{
return false;
}
try
{
Socket testConnectSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
testConnectSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
testConnectSocket.Connect("8.8.8.8", 53);
testConnectSocket.Shutdown(SocketShutdown.Both);
testConnectSocket.Close();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}