How to Create multiple Sockets in a same program.?

892 Views Asked by At

I was writing a program that has two sockets bounded to two distinct ports. I have created an object of another program, which is in a separate file(It also has a socket initialized and bounded to a separate port). I get a runtime exception and when i tried to print the WSAGetLastError it returned err code:10093.

What i want to know is, how can i use WSAStartup() and WSACleanup(). Do i need to call WSAStartup() for each socket and call WSACleanup() thrice.

Can someone help me to overcome this problem. Thanks in advance..:-)

2

There are 2 best solutions below

3
On

You should call WSAStartup()/WSACleanup() on a per-program basis, i.e. once per program.

0
On

You only need to call WSAStartup once (in your address-space\process), when you are using the winsock dll, and WSACleanup when you have finished using the sockets.

I typically implement the start-up\cleanup by doing something like: (This is really only safe for single-threaded applications, but using a mutex for multi-threaded isn't difficult...)

class HigherLevelSocketWrapper
{
private:
    static int m_iInstanceCount = 0;

public:
    HigherLevelSocketWrapper()
    { 
        //Check if m_iInstanceCount is 0, if so, call WSAStartup.
        //increment m_iInstanceCount
    }
    virtual ~HigherLevelSocketWrapper()
    { 
        //decrement m_iInstanceCount
        //Check if m_iInstanceCount is 0, if so, call WSACleanup.
    }
};