0

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 Answers2

3

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks, I have called WSAStartup() and WSACleanup() as you have suggested. But i get the same error at this point `IP=inet_ntoa(*(struct in_addr *)*hostEntry->h_addr_list);` When i tried to debug, hostEntry returns null. Here, `hostEntry = gethostbyname(hostId);` – rutharanga May 21 '12 at 10:38
  • @rutharanga If `gethostbyname` returns `NULL` you should check `WSAGetLastError` immediately. – Some programmer dude May 21 '12 at 10:47
  • @rutharanga Think about moving towards `getaddrinfo()/getnameinfo()` instead of `inet_ntoa()` and `gethostbyname()`... – glglgl May 21 '12 at 10:48
0

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.
    }
};
Jeremy
  • 824
  • 1
  • 9
  • 21