MFC Sockets and "Address already in Use" problem...

Posted on 2002-05-26
Last Modified: 2013-11-20
Dear Friends,
   I have a simple server program using MFC sockets to receive requests from client applications on TCP/IP and respond with some data. The application basically creates a socket, binds it to a IP address and starts listening on a specific port. I have a problem here.
   Randomly the application exits with an error message "Address already in use" indicating the port number being used for listening is already in use. But I have used different port numbers which I am sure are not used elsewhere and I still get this error. Unfortunately the occurance is random. Sometimes the problem does not get solved even after restarting the computer.
   I have a feeling that when the earlier instance of this socket program exits it might not be doing a graceful shutdown and hence traces of the connection made by it are still remaining causing the next instance to fail. To be on the safer side I would like to do a "scoket deinitialisation" first and then start the application so that any old traces are removed. Can someone suggest how one could do a socket deinitialisation so that the program that starts is fail proof?

Question by:ganeshokade
LVL 32

Expert Comment

ID: 7035107
I know of no sure fire way other than a reboot.  If you have an application listening on a socket and it aborts it's quite possible that the socket will be left in the listening state.  Now I've seen this clear up spontaneously after a variable wait time (sometimes as long as an hour...) and other times it never clears.  I suspect it just depends on what the state of the socket was when it happened.  Since I know of no way to get the handle to the socket, there is no way to close it.

So unless someone here knows a trick to get at this, I think the answer is going to be:

1) Be more careful about leaving sockets hanging.  Careful application design should permit you do get control and cleanup in all but the most dire situation.  Trap the Top Level Exception is you have to.

2) If your application starts and cannot get its socket, warn the user and request a reboot.
LVL 30

Expert Comment

ID: 7036175

You could confirm wheather or not this is the problem, by writing to an INI file when the connection is made, and then  writing when the connection is closed.

This would be easy to do using WritePrivateProfileString function.
Open connection could have something like the following code:
CString SectionName;
SectionName.Format("SocketNumber %i", mycsocket.m_hSocket);
CString KeyName;
KeyName.Format("PortNo%i_Open", PortNo);
CString Value = "Open connection";
WritePrivateProfileString(SectionName, KeyName, Value, "MyFileLogName.ini");

Close connection can have something like the following:
CString SectionName;
SectionName.Format("SocketNumber %i", mycsocket.m_hSocket);
CString KeyName;
KeyName.Format("PortNo%i_Close", PortNo);
CString Value = "Close connection";
WritePrivateProfileString(SectionName, KeyName, Value, "MyFileLogName.ini");
LVL 30

Expert Comment

ID: 7036183
If you're afraid that your log file is going to get to big, you could just have the Close connection function remove the entry made by previous connection.
CString SectionName;
SectionName.Format("SocketNumber %i", mycsocket.m_hSocket);
CString KeyName;
KeyName.Format("PortNo%i_Close", PortNo);
WritePrivateProfileString(SectionName, KeyName, NULL, "MyFileLogName.ini");

LVL 22

Accepted Solution

ambience earned 100 total points
ID: 7040959
i think what you are missing is


winsock would not allow an address to be reused after a socket has been bound to an address, and even after the socket is closed there is a time period during which no other socket can bind to that address. By specifying SO_REUSEADDR you are supressing such behaviour and maybe this is all you need.

In MFC that would be CAsyncSocket::SetSockOpt

Author Comment

ID: 7126962
That's the nearest one. There seems to be a bug in the Win 2K SP2.0 which is causing this problem - still not resolved. It occurs the VERY FIRST time I run the socket application on a freshly installed win 2k advanced server with SP 2.0!

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
isEverywhere  challenge 19 71
zeroMAx challenge 20 86
My project did see openJDK that I installed. What could be the problem 7 121
Path of Workbook 3 59
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.
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at

930 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now