Unhandled Exception: System.Net.Sockets.SocketException: The requested address is not valid in its context

Brown, Matt 106 Reputation points
2023-07-18T21:07:20.1733333+00:00

The code below generates an error at the point of the last line of the example code. The error is listed below the code sample. I even went and hardcoded the value which was being returned from the app.config file as to make sure that wasn't the issue, and yet the error is still produced. What I don't understand is, the error makes a reference to a TcpListener which is used in a different function. The instance ID in question is 999 or 777 depending on if it is in dev or prod.

void Listener::waitForMessage(){
	array<Byte> ^buffer = gcnew array<Byte>(1024);
	String ^data = nullptr;
	Int32 len;
	Parser^ parser = Parser::getInstance();
	long long elapsed, nowtime, prevtime, delayTime;
	DateTime now = DateTime::Now;
	bool isPrimary;
	String ^failcode = "RESTART";

	String^ type = System::Configuration::ConfigurationManager::AppSettings["serverType"];
	if (!String::IsNullOrEmpty(type) && type->Equals("PRIMARY")){
		isPrimary = true;
	}
	else{
		isPrimary = false;
	}

		log->logInfo("Starting Listener Server");
		server->Start();		
		//Send startup message
		String ^iid = System::Configuration::ConfigurationManager::AppSettings["instanceId"];
Unhandled Exception: System.Net.Sockets.SocketException: The requested address is not valid in its context
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at ENS.Listener.waitForMessage() in C:\Desktop-Apps\ensservice\ENSService\Listener.cpp:line 92
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,433 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,856 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Brown, Matt 106 Reputation points
    2023-07-19T15:59:02.3966667+00:00

    This is the complete file and not complete application.

    #include "Listener.h"
    #include "Parser.h"
    
    
    
    using namespace System::Configuration;
    using namespace System;
    using namespace System::IO;
    using namespace System::Net;
    using namespace System::Net::Sockets;
    using namespace System::Threading;
    using namespace ENS;
    using namespace ENSAssembly;
    
    Listener::Listener(void)
    {
    	log = LoggerPool::getInstance()->getLog(LOG_TYPE::LISTENER);
    	if(log == nullptr){
    		throw gcnew IOException("Failed to create listener log");
    	}
    	IPAddress^ localAddr;
    	String ^tport = System::Configuration::ConfigurationManager::AppSettings["port"];
    
    	if(String::IsNullOrEmpty(tport)){
    		tport = "6550";
    	}
    	port = System::Convert::ToInt32(tport);
    	log->logInfo("Port: " + port);
    	localip = System::Configuration::ConfigurationManager::AppSettings["serverIp"];
    	if(String::IsNullOrEmpty(localip) || (localip->Equals("localhost"))){
    		localAddr = IPAddress::Parse( "127.0.0.1" );
    	}else{
    		localAddr = IPAddress::Parse(localip);
    	}
    	//create the server
    	log->logInfo("listening on: " + localAddr);
    	server = gcnew TcpListener(localAddr, port);
    
    	//check the last time the application started. Will be used to determine if a page is needed.
    #if DEBUG
    	string applicationName =
    		Environment.GetCommandLineArgs()[0];
    #else 
    	String^ applicationName =
    		Environment::GetCommandLineArgs()[0];
    #endif
    
    	String^ exePath = System::IO::Path::Combine(
    		Environment::CurrentDirectory, applicationName);
    
    	System::Configuration::Configuration^ config = System::Configuration::ConfigurationManager::OpenExeConfiguration(exePath);
    	lastStart = config->AppSettings->Settings["lastStart"]->Value;
    	String^ nowTicks = DateTime::Now.Ticks + "";
    	config->AppSettings->Settings["lastStart"]->Value = nowTicks;
    	config->Save(ConfigurationSaveMode::Modified);
    
    }
    
    
    
    Listener::~Listener(void){
    	if(server != nullptr)
    		server->Stop();
    }
    
    
    void Listener::waitForMessage(){
    	array<Byte> ^buffer = gcnew array<Byte>(1024);
    	String ^data = nullptr;
    	Int32 len;
    	Parser^ parser = Parser::getInstance();
    	long long elapsed, nowtime, prevtime, delayTime;
    	DateTime now = DateTime::Now;
    	bool isPrimary;
    	String ^failcode = "RESTART";
    
    	String^ type = System::Configuration::ConfigurationManager::AppSettings["serverType"];
    	if (!String::IsNullOrEmpty(type) && type->Equals("PRIMARY")){
    		isPrimary = true;
    	}
    	else{
    		isPrimary = false;
    	}
    
    		log->logInfo("Starting Listener Server");
    		server->Start();		
    		//Send startup message
    		String ^iid = System::Configuration::ConfigurationManager::AppSettings["instanceId"];
    		// String^ iid = "777";
    
    		if (String::IsNullOrEmpty(iid)){
    			iid = "777";
    		}
    
    		if (isPrimary){
    			//check last start time. We only want to page if this is the primary server. Backup can just email.
    			if (lastStart != nullptr){
    				nowtime = now.Ticks;
    				prevtime = Int64::Parse(lastStart);
    				if (prevtime == 0){
    					prevtime = nowtime;
    				}
    				// A single tick represents one hundred nanoseconds or one ten-millionth of a second. 
    				//			 There are 10,000 ticks in a millisecond, or 10 million ticks in a second. 
    				elapsed = nowtime - prevtime; 
    			}
    			else{
    				elapsed = 0;
    			}
    
    			delayTime = (MIN_TO_PAGE * 60 * 10000000);
    			//has it restarted in the last XX minutes?
    			if (elapsed < delayTime){ //convert to ticks, see calc above
    				//want to send page. 
    				failcode = "PAGE";
    				log->logInfo("Recently restarted, triggering page. Elapsed time: " + elapsed + " DelayTime: " + delayTime);
    			}
    			else{
    				log->logInfo("Restarted, not triggering page. Elapsed time: " + elapsed + " DelayTime: " + delayTime);
    			}
    		}
    
    		log->logInfo("Last Start: " + lastStart + " Now: " + nowtime);
    		String^ timestring = now.ToString("yyyy-MM-dd HH.mm.ss");
    		parser->processMessage("ESPWTO5I 11111 TEST " + timestring + " ENSSTART ENSPROD 11111 ENS#PROD 1 EXEC " + failcode + " " + iid + " ENS2 $IPS ESP(V826772) " + localip);
    
    		while(true){
    			try{
    				if(server->Pending())
    				{
    					TcpClient^ client = server->AcceptTcpClient();
    					data = nullptr;
    					
    					NetworkStream^ stream = client->GetStream();
    					do{
    						try{
    							if (!client->Connected){
    								client->Close();
    							}
    							do
    							{
    								len = stream->Read(buffer, 0, buffer->Length);
    								data = String::Concat(data, Text::Encoding::ASCII->GetString(buffer, 0, len));
    							} while (stream->DataAvailable);
    							//len = stream->Read(buffer, 0, buffer->Length);
    							//data = String::Concat(data, Text::Encoding::ASCII->GetString(buffer, 0, len));
    							
    							if (data->Length >= 8){
    								//check if this is a real request
    								if (!data->StartsWith("ESPWTO") && !data->StartsWith("CA7SMF3") && !data->StartsWith("ENSTEST") 
    									&& !data->StartsWith("MARAEMER") && !data->StartsWith("SNOW_CREATE")){
    									//break the connection, probably a improper scan.
    									client->Close();
    									log->logInfo("Discarding message, threw global exception. Data is: " + data);
    									data = "BADDATA";
    									break;
    								}
    							}
    						}catch(...){
    							//blow this joint!
    							client->Close();
    							log->logInfo("Discarding message, threw global exception. Data is: " + data);
    							data = "BADDATA";
    							break;
    						}
    					}while ( stream->DataAvailable );
    
    					data = data->Trim();
    					log->logInfo("Listener received: " + data);
    
    					if(data->StartsWith("ESPWTO5I") || data->StartsWith("ESPWTO6I") || data->StartsWith("CA7SMF3") 
    						|| data->StartsWith("ENSTEST") || data->StartsWith("MARAEMER") || data->StartsWith("SNOW_CREATE")){
    						array<Byte>^ack = Text::Encoding::ASCII->GetBytes( "ACK");
    						stream->Write(ack, 0, 3);
    						String ^ip = (((IPEndPoint^)(client->Client->RemoteEndPoint))->Address)->ToString();
    						client->Close();
    						if (data->StartsWith("CA7SMF3")){
    							data = data + " NOREPLY";
    						} else if (!data->StartsWith("MARAEMER")){
    							data = data + " " + ip;
    						}
    						
    						parser->processMessage(data);
    					}else{
    						//ignore GET & HELP request from port scan.
    						log->logInfo("Discarding message (doesn't start with ESPWTO5I or ESPWTO6I): " + data);
    						client->Close();
    					}
    					log->logInfo("-----------------------------------------------");
    				}else{
    					if(shutdown){
    						log->logInfo("Listener exiting.");
    						server->Stop();
    						log->Close();
    						delete log;
    						delete server;
    						log = nullptr;
    						server = nullptr;
    
    						return;
    					}else{
    						Thread::Sleep(PENDING_SLEEP_TIME);
    					}
    				}
    			}catch(SocketException^ e){
    				log->logInfo("Error: " + e->ErrorCode + " " + e->Message);
    			}catch(IOException^ ioe){
    				log->logError(gcnew String(__FUNCTION__), "Error: " + ioe->Message, ioe);
    			}
    		}
    	
    }
    
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.