<p>Greetings,  I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination.  My pseudocode looks like this:</p>

<pre><code>ClassA a = new ClassA(); //(class A  instantiates socket and binds it to 127.0.0.1:4567) 
//do something 
//...much later, a has been garbage-collected away.
ClassA aa = new ClassA(); //crash here.
</code></pre>

<p>At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true.  But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567.  What do I do to be able to 'un-bind' the socket?</p>

<hr>

<p>EDIT: I'm not relying solely on garbage collection (though I tried that approach as well).  I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.</p>

<hr>

<p>EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect).  Let me try calling .Dispose directly and get back to you.</p>

<hr>

<p>EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.</p>

<p>Any help would be appreciated!</p>

[{'answer_id': 48361, 'author': 'zappan', 'author_id': 4723, 'author_profile': 'https://Stackoverflow.com/users/4723', 'pm_score': 0, 'selected': False, 'text': "<p>you can't rely on object being garbage collected in C# (i assume you're using c#, based on tagging) if it holds resources like being bound to the network resource like in your example, or holding some other kind of stream, a file stream would be a common example.</p>\n\n<p>you have to assure to release the resources that the object is holding, so that it can be garbage collected. otherwise it won't be garbage collected, but remain living somewhere in the memory. your pseudocode example doesn't provide that you're doing the resources releasing, you just state that the object gets (should get) garbage collected.</p>\n"}, {'answer_id': 48362, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 0, 'selected': False, 'text': '<p>The garbage collector doesn\'t guarantee you that the socket will ever be closed. For a complete example read this <a href="http://msdn.microsoft.com/en-us/library/fx6588te.aspx" rel="nofollow noreferrer">MSDN example</a>.</p>\n\n<p>The main point is to actually call <code>Socket.Close()</code> as soon as possible. For example, ClassA could implement <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow noreferrer">IDisposable</a> and use it like this:</p>\n\n<pre><code>using (ClassA a = new ClassA()) \n{\n    // code goes here\n}\n// \'a\' is now disposed and the socket is closed\n</code></pre>\n'}, {'answer_id': 48369, 'author': 'VolkerK', 'author_id': 4833, 'author_profile': 'https://Stackoverflow.com/users/4833', 'pm_score': 0, 'selected': False, 'text': '<p>The garbage collector runs the finalizer of the object at some indeterminate time.\nYou could implement the IDisposable interface and call the Dispose() method before the object looses Scope - or let the using statement do that for you.</p>\n\n<p>see <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.idisposable.aspx</a> and <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/yh598w02.aspx</a></p>\n\n<p>edit: works fine for me</p>\n\n<pre>\nusing System;\nusing System.Net.Sockets;\nusing System.Net;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        class ClassA : IDisposable\n        {\n            protected Socket s;\n            public ClassA()\n            {\n                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n                s.Bind(new IPEndPoint(IPAddress.Any, 5678));\n            }\n\n            public void Dispose()\n            {\n                s.Close();\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            using(ClassA a=new ClassA()) {\n            }\n            using (ClassA b = new ClassA())\n            {\n            }\n        }\n    }\n}\n</pre>\n'}, {'answer_id': 48383, 'author': 'AlexeyMK', 'author_id': 5021, 'author_profile': 'https://Stackoverflow.com/users/5021', 'pm_score': 3, 'selected': True, 'text': '<p>(this is what finally got everything to work for me)</p>\n\n<p>Make sure EVERY socket that the socket in A connects to has </p>\n\n<pre><code>socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);\n</code></pre>\n\n<p>set upon being initiated.  </p>\n'}, {'answer_id': 1497357, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>The best solution is to retry to bind the socket a few times (2-3). On the first attempt, if it fails, i have found that it will properly (and permanently) close the original socket.</p>\n\n<p>HTH,</p>\n\n<p>_NT</p>\n'}]
['https://Stackoverflow.com/questions/48356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5021/']