Solved

How to close a socket in C#?

Posted on 2008-06-18
11
1,064 Views
Last Modified: 2013-12-16
Is there any way to close a socket if you know the port number?
0
Comment
Question by:Tharo_Systems
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21815598
Not if you don't own it.
0
 

Author Comment

by:Tharo_Systems
ID: 21815616
I have a program that opens a socket for listening. I need to be able to close it from a different function.
0
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21816173
And do you have the source for that program?  Can we see it?
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 

Author Comment

by:Tharo_Systems
ID: 21816315
Here's the function that creates the socket. I would like to have another function that closes the socket.
private void CreateListenerSocket(int PortToListenOn)
	{
		// Determine the IP address of the machine
		IPAddress [] aryLocalAddr = null;
		try
		{
			IPHostEntry ipEntry = Dns.GetHostEntry( Dns.GetHostName() );
			aryLocalAddr = ipEntry.AddressList;
		}
		catch( Exception ex )
		{
			theLog.WriteEntry("Error trying to get local address {0}: " + ex.Message, EventLogEntryType.Error);
		}
		// Verify that an address was obtained. Write to the log if not.
		if( aryLocalAddr == null || aryLocalAddr.Length < 1 )
		{
			theLog.WriteEntry("Unable to get local address", EventLogEntryType.Error);
			return;
		}
                listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
		listener.Blocking = false;
		for (int i = 0; i < aryLocalAddr.Length; i++)
                {
                  if (aryLocalAddr[i].AddressFamily == AddressFamily.InterNetwork)
                  {
                    listener.Bind(new IPEndPoint(aryLocalAddr[i], PortToListenOn));
                    break;
                }
            }
	listener.Listen( 10 );
	listener.BeginAccept( new AsyncCallback( OnConnectRequest ), listener );
	}

Open in new window

0
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21816399
If you keep a reference to your listener variable handy it's as simple as calling listener.Close();
0
 

Author Comment

by:Tharo_Systems
ID: 21816486
I was hoping it would be a simple answer. I'm very new to this. Can you elaborate on how to do that? Thanks!
0
 
LVL 18

Expert Comment

by:jcoehoorn
ID: 21816555
Well, the method you posted doesn't declare listener anywhere, so I'm assuming it's a class-level variable.  With that in mind, you can just say this in any non-static method in your class and the socket will close:

if (listener!= null) listener.Close();

That's it.
0
 

Author Comment

by:Tharo_Systems
ID: 21821125
Can it be done from another class?
0
 

Author Comment

by:Tharo_Systems
ID: 21821250
OK, I tried adding that code before the line that creates the socket. I want to prevent the program from opening more than one. The first time through, it's fine because listener is null. The second time it's called, it does close listener, but when it hits the "listener = new socket..." line, it crashes. Am i doing something wrong? Thanks!
private void CreateListenerSocket(int PortToListenOn)
	{
		// Determine the IP address of the machine
		IPAddress [] aryLocalAddr = null;
		try
		{
			IPHostEntry ipEntry = Dns.GetHostEntry( Dns.GetHostName() );
			aryLocalAddr = ipEntry.AddressList;
		}
		catch( Exception ex )
		{
			theLog.WriteEntry("Error trying to get local address {0}: " + ex.Message, EventLogEntryType.Error);
		}
		// Verify that an address was obtained. Write to the log if not.
		if( aryLocalAddr == null || aryLocalAddr.Length < 1 )
		{
			theLog.WriteEntry("Unable to get local address", EventLogEntryType.Error);
			return;
		}
 
            try
            {
                if (listener != null)
                {
                    listener.Close();
                }
            }
            catch (Exception ex)
            {
                theLog.WriteEntry(ex.Message, EventLogEntryType.Error);
            }  
 
                listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
		listener.Blocking = false;
		for (int i = 0; i < aryLocalAddr.Length; i++)
                {
                  if (aryLocalAddr[i].AddressFamily == AddressFamily.InterNetwork)
                  {
                    listener.Bind(new IPEndPoint(aryLocalAddr[i], PortToListenOn));
                    break;
                }
            }
	listener.Listen( 10 );
	listener.BeginAccept( new AsyncCallback( OnConnectRequest ), listener );
	}
 

Open in new window

0
 

Author Comment

by:Tharo_Systems
ID: 21821525
Upon further inspection, it seems it's crashing when it tries to access aryLocalAddr. Not sure why, but I'm getting "system.objectdisposedexception" errors. Any ideas? I also want to be able to close the socket completely by a button/checkbox/whatever in a separate configuration window in a different class, but I don't know how to access listener from there. Thanks!
0
 
LVL 18

Accepted Solution

by:
jcoehoorn earned 500 total points
ID: 21821890
Any other class that needs to use the listener member will then need a reference to the correct instance of this class, and listener will need to be public- preferably exposed as a property.

Not sure what's going on with aryLocalAddr.  Calling listener.Close() is the exact same thing as disposing (calling listener.Dispose()) - the two are interchangeable, if that helps.  Is seems that two are intertwined there somehow.  The error puzzles me because if closing the socket also disposed the the IPEndPoint then I would expect it to dispose of the individual items in the array and not the array itself.  That would leave with an error message complaining about aryLocalAddr[n] rather than aryLocalAddr itself.
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
.NET - find out if application is running on Windows 2012 server 3 55
How to set focus on a dynamic control 18 47
asp.net repeater 2 32
Convert a string to date 4 39
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question