CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    WSAStartup best practices?

    I'm writing a network-related module for a larger project. It's cross-platform, and the Windows implementation uses Winsock2.

    I'm having some trouble figuring out the best way to handle the need to call WSAStartup()/WSACleanup(). If these things were reference-counted in some way, then the correct thing would be obvious; just make sure to call WSAStartup() in my object's constructor and WSACleanup() in the destructor. However, they aren't as far as I can tell, which makes calling WSACleanup() at any time perilous. An unrelated part of the code might also be trying to use sockets, and I don't want to rip them out from under it! I'm guessing, but I'm not certain, that calling WSAStartup() multiple times does no harm.

    Any tips on best practices here?

  2. #2
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: WSAStartup best practices?

    The online documentation of WSAStartup says
    "An application must call the WSACleanup function for every successful time the WSAStartup function is called. " (http://msdn.microsoft.com/de-de/libr...=vs.85%29.aspx)
    So maybe your approach with your object's c'tor/d'tor is not completely wrong.

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: WSAStartup best practices?

    Wrap your code (in a class) such that before you use a socket, you call WSAStartup and when you are finished with the socket, you call WSACleanup. The docs mention that the startup calls are ref counted and only the last cleanup call unloads the dll.

    Assuming that your code makes corresponding 1:1 calls in terms of WSAStartup and WSACleanup, you won't yank the rug out from socket calls made from other parts of the code because they too have made at least one WSAStartup call (and *should* make at least one WSACleanup call).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured