DWise1's Sockets Programming Pages: Winsock

DWise1's Page on Converting Sockets Programming to WinSock


Cartoon depicting Bill Gates making two different public statements at different times:
  • in 1994: "There is no need for Microsoft to support TCP/IP."

  • in 1995: "Microsoft has invented a new protocol. We're calling it TCP/IP."

I'm sure that I'm not the only programmer to find himself in this situation: all of my network programming projects are for Windows, but almost all of the information and examples out there are for Unix. Well, thanks to sockets programming and WinSock, many Unix sockets programs convert fairly easily to Windows.

On this page, I will review the basic changes that are needed to convert a Unix sockets program to a working Winsock program and I will provide links to other sites that provide more information on Winsock.


Topics


A Little History

A protocol stack consists of hardware and software for all the layers. One of the problems this caused is that there was little or no standardization from one vendor's stack to another's, which complicated software development and would tie software applications to a specific vendor's protocol stack.

Around 1990, several groups from different companies developed a single API for Windows that could run on any vendor's stack. They based it on another existing API, BSD sockets, and called it Windows Sockets, AKA "WinSock 1.1". In the process, they carried many of the concepts and functions straight over from BSD sockets (lucky for us!) and then extended them with additional functions. The Winsock extensions are prefixed with "WSA" while the BSD functions retain their original names.

Then in 1994, they came out with the Winsock 2 specification which changed the API architecture to provide even more enhanced features, including the ability to simultaneously access multiple transport protocols and protocol stacks other than TCP/IP. WinSock 2 also incorporated the Windows Open System Architecture (WOSA), which requires each vendor to be compatible with the standard WinSock DLL. Before this, each vendor's interface between the WinSock DLL and the stack was different and proprietary and so you needed a different DLL for each stack you had installed. Now you can access stacks from different vendors simultaneously using the same WinSock DLL, a definite improvement.

The current Winsock specification version, 2.2.2, was released on 07 August 1997 and can be obtained at ftp://ftp.microsoft.com/bussys/winsock/winsock2.


The Basic "How to Convert from UNIX to Winsock"

Changing UNIX sockets code to Winsock requires an amazingly small number of changes. That is, of course, assuming that the rest of the program doesn't use features that are peculiar to UNIX (see the "Caveat" section below).

A good source for information on converting UNIX sockets code to Windows is the document, Transitioning from UNIX to Windows Socket Programming, by Paul O'Steen. This PDF file also gives complete instructions with pictures for creating in Visual C++ 6.0 a Win32 console application (equivalent to a DOS application) that supports WinSock.

Examples of UNIX applications that have been converted to Windows can be found at the site for the book, The Pocket Guide to TCP/IP Sockets: C Version, by Michael J. Donahoo and Kenneth L. Calvert:

Similar examples for the second edition, TCP/IP Sockets in C: Practical Guide for Programmers, can be found through that book's page.


The following is a basic overview of Winsock programming, concentrating mainly on the basic steps required to convert a UNIX sockets program to WinSock for Win32. The individual topics covered are:


Linking the Winsock Library to Your Project

The actual procedure and name of the library name will vary between different compilers, so you will need to verify what that procedure is and the library name it uses. The two that I use are:


Absolutely Necessary Changes

  1. Replace the UNIX-specific header includes with the single include statement
    #include <winsock.h>
    or, for Winsock2:
    #include <winsock2.h>
  2. Within the program, run the Winsock initialization with the following code
    1. Include the data declaration:
      WSADATA wsaData;

    2. Add the function call and completion test:
      if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
      {
      // insert error-handling code here
      }
    The parameter, MAKEWORD(2, 0), specifies the WinSock version number (version 2.0 in this example) and formats it correctly.

  3. Replace the UNIX close() function call with closesocket().

  4. At the end of the program, exit the WinSock DLL by calling the function, WSACleanup().

  5. Read error codes with WSAGetLastError().

    Winsock Error Codes
    WSAGetLastError() only returns a numeric value for the error code instead of any explanatory text. The authoritative reference for what those numbers mean is in the Microsoft Developers' Network Library: Windows Sockets Error Codes.


Optional but Advisable Changes

These are changes that should be made when converting UNIX sockets code to Winsock, but your code will still work if you don't.

For example, in UNIX sockets are a type of file, so a socket is a file descriptor, which is an int. However, in Winsock a socket is a handle, which has to be treated differently from an int. This is why Winsock needs a special function, closesocket(), instead of being able to use the more generic function for closing a file, close(). It's also why select(), which can only be used on sockets, cannot also be used to test the stdin standard input file, as it can be used in UNIX. So a Winsock socket is declared as SOCKET, which is typedef'd as an unsigned int. You could continue to use the UNIX convention of declaring your sockets as int and your code will still work, but it is likely to confuse others who read your code later on.

So that is the main reason for making these changes: in order to conform with the naming conventions of the Winsock programming community so that others can read and understand your code and you can read and understand theirs. Indeed, in my earlier Winsock work I ignored these changes and kept to the UNIX standard, but then found in sharing that code with other beginners that it was a source of confusion for them.

These are some of the Winsock #define's and typedef's you will most likely encounter:

Winsock Name UNIX Equivalent Note
SOCKET int In UNIX a socket is a file descriptor and is declared as an int.
In Winsock it's a handle and is typedef'd as an unsigned int.
INVALID_SOCKET -1 In UNIX, a function that fails to create a socket returns the standard error value of -1. However, in Winsock a SOCKET cannot take a negative value, so INVALID_SOCKET is #define'd as (SOCKET)(~0), which, if interpreted as an int, would be equal to -1.
SOCKET_ERROR (-1) This just gives a name to the standard error value of -1 which is returned by the sockets functions that do not return a socket. Care should be taken to avoid assigning SOCKET_ERROR to a SOCKET, or to comparing a SOCKET with SOCKET_ERROR; INVALID_SOCKET should be used instead.
SOCKADDR struct sockaddr This typedef eliminates the need in C to always include the keyword struct.
SOCKADDR_IN struct sockaddr_in This typedef eliminates the need in C to always include the keyword struct.
HOSTENT struct hostent This typedef eliminates the need in C to always include the keyword struct.
SERVENT struct servent This typedef eliminates the need in C to always include the keyword struct.


The WSA* Extended Functions

While Winsock supports almost all of the functions in the sockets API, it also provides a number of functions which extend the API, including extended versions of the standard functions. These extensions cover many advanced concepts peculiar to Winsock, such as socket I/O, quality of service (QoS), and socket groups. Other extensions tie into Windows programming rather nicely, enabling the programmer to work with events and with Windows messages.

For example, the Winsock extended version of select() is WSAAsyncSelect(). Whereas select() works for sets of sockets in which you must test each possible socket, each call to WSAAsyncSelect() sets up the testing of one specific socket for the set of network events you're interested in. When one of those events happens, the window indicated in WSAAsyncSelect() will receive a message notifying it of that event and so it can handle that event only when it happens and needn't do anything about that socket until there is actually something to do. Contrast that with the need to repeatedly loop back to select() in order just to test whether anything happened.

Obviously, this would be an area for further study if you're planning on doing Windows programming. However, my main interest is and has been in basic sockets and in writing portable code (ie, code that could be ported easily to UNIX/Linux), so I've not looked into this yet. As a result, I also do not know of any resources to recommend.


Caveat Programmer

Since so many of the BSD socket functions were carried over directly to WinSock, most UNIX sockets programming should translate easily over to Windows. However, you should keep a few caveats in mind:


Those are just the main differences and caveats that the beginner is likely to have to deal with. You can find more detailed information on issues of compatibility between WinSock and BSD sockets and between WinSock 1.1 and WinSock 2 at:


Resources

Books

  • Network Programming for Microsoft Windows
    By Anthony Jones and Jim Ohlund, Microsoft Press, 1999, 675 pages, ISBN 0-7356-0560-2.

    This book covers a fairly wide range of topics, mainly using Winsock but not MFC. It even gets into raw sockets (for the highly experienced only). There's a lot of material for a beginner to absorb as his first exposure to the subject. This was the first book I picked up on the subject (besides a come-up-to-speed-quick book on TCP/IP -- see below) and I intend to come back to it as I progress.

    The second edition was published in 2002 and is listed here on Amazon.com (800 pages, ISBN 0-7356-1579-9). This edition reportedly concentrates more on sockets and on Microsoft's new whiz-bang networking services, relegating the first book's coverage of "legacy APIs" (eg, NetBIOS, Mailslots, and Named Pipes) to the CD (one reviewer's complaint is that this was only mentioned in the introduction). Another complaint is that the examples use XP's new name resolution functions and so will not compile unless you have downloaded the latest SDK.


  • Windows Sockets Network Programming
    By Bob Quinn, Dave Shute (Contributor), David K. Shute, Addison-Wesley Advanced Windows Series, 1995, 637 pages, ISBN 0-2016-3372-8.

    This book is well-enough received on Amazon.com, but it is criticized mainly for being dated and for concentrating more on Win16 sockets programming than on Win32. On the plus side, if you are going to be doing Win16 sockets programming, then this book may be of more use to you than the more recent offerings.

    This book provided much of the material at the SOCKETS: WinSock Development Information site. The book's web site is at http://www.sockets.com/wsnp.htm.


  • Win32 Network Programming: Windows(R) 95 and Windows NT Network Programming Using MFC
    By Ralph Davis, Addison-Wesley, 1996, 675 pages, ISBN 0-7356-0560-2.

    Reviewed on Amazon.com


  • Internetworking with TCP/IP Vol. III Client-Server Programming and Applications-Windows Sockets Version
    By Douglas E. Comer, David L. Stevens (Contributor), Prentice Hall, 1997, 512 pages, hardcover, ISBN 0-1384-8714-6.

    Reviewed on Amazon.com


  • Web Sites

  • Microsoft Developers Network (MSDN) Library
    This is the "horse's mouth" with articles and reference documentation their supported software development tools. It's a must-have link for all programmers developing software for a Windows environment.

    A few pertinent links for Winsock are:

  • Winsock Programmer's FAQ
    This is the FAQ for the alt.winsock.programming and comp.os.ms-windows.programmer.tools.winsock newsgroups. It serves as a repository of Winsock programming information and links.

  • The UNIX Socket FAQ
    Almost more of a newsgroup than a FAQ. Users post their questions and other users try to help them.
    Check the rules before you reveal yourself to them as a newbie.

  • WinSock Development Information
    Source code, development tools, and other resources.

  • The Windows Sockets 2 API Specification
    Available as a Microsoft Word document at the WinSock Development Information site. This document details the differences between Winsock and BSD sockets.

  • Winsock's Compatibility With BSD Sockets by Warren Young
    An article on the Winsock Programmer's FAQ site which delves more deeply into the compatibility issues.

  • Transitioning from UNIX to Windows Socket Programming by Paul O'Steen.
    A good source for information on converting UNIX sockets code to Windows. This PDF file also gives complete instructions with pictures for creating a Win32 console application (equivalent to a DOS application) that supports WinSock.

  • Examples of UNIX applications that have been converted to Windows
    Examples of UNIX applications that have been converted to Windows can be found at the site for the book, The Pocket Guide to TCP/IP Sockets: C Version, by Michael J. Donahoo and Kenneth L. Calvert:

  • The Winsock Tutorial
    This appears to be a fairly good introductory tutorial for writing WinSock applications. Its example programs include both TCP and UDP client and server programs and a DNS name resolver.

  • Return to Top of Page
    Return to DWise1's Sockets Programming Page
    Return to DWise1's Programming Page

    Contact me.


    Share and enjoy!

    First uploaded on 2003 July 26.
    Updated on 2011 July 18.