Ok this is kind of frustrating, from past few hours i was struggling with .Net Socket based application, in short this application acts a async server, and this server can be instantiated in 2 ways :-
- First way is to start the server is by getting local DNS name of the computer and then bind it to the socket object.(this works totally fine)
- Second way is to start the server is by getting host name from the user input such as "192.168.1.2" and then i was trying to bind it to the socket object but it keeps shooting the exception. Precisely speaking this exception only raised when i try to use IPv4 Private network based IP's.
I seriously have no idea why is that happening
Exception : "The requested address in not valid in its context".
Code below is used to start the server
public void StartServer(int port, IPAddress ipAddress)
{
byte[] bytes = new Byte[1024];
IPAddress[] ips = Dns.GetHostAddresses(ipAddress.ToString());
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._socket = listener;
try
{
IPEndPoint bindEndPoint;
bindEndPoint = new IPEndPoint(ipAddress, port);
listener.Bind(bindEndPoint);
listener.Listen(100);
WriteStatus("\nStarted -" + bindEndPoint.ToString() + " on " + Convert.ToString(port));
IsUp = true;
while (IsUp)
{
allDone.Reset();
WriteStatus("\nWaiting for a connection......");
try
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (ObjectDisposedException)
{
return;
}
allDone.WaitOne();
}
}
catch (SocketException se)
{
MessageBox.Show(se.Message, "Error : Start Server", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
This way it loads the Pre-configured DNS name
private void LoadStaticIp()
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
_ipAddress = ipHostInfo.AddressList[0].ToString();
}
Please help.