Wednesday, February 22, 2006

Porting Berkeley Sockets

Over the past few days I've had the opportunity to port a program using Berkeley sockets to Winsock. It's actually a lot easier than it sounds.

A large part Winsock was designed based on Berkeley sockets, and for the most part, the only things that have been changed are a few function names. I'll touch on the main one's you'll run into while porting.

read / write The functions used for I/O (Input and output) operations on a socket.
read(socketfd, buf, left);
write(socketfd, buf, left);

In Winsock 2 the functions are nearly the same, except under the name send and recv
int recv(SOCKET s, char* buf, int len, int flags);
int send(SOCKET s, const char* buf, int len, int flags);

The extra parameter flags is for special things like just peeking the recv stream instead of removing from it. If you want to do a direct port, you can just set flags to 0 and keep the other parameters the same.

fcntl Change the I/O mode on a socket, in this case, change the socket to nonblocking.
fcntl(fd, F_SETFL, O_NONBLOCK);

Once again, Winsock 2 is very similar, with a few extra features. To put the socket into nonblocking using Winsock 2 you have to use the following method:
unsigned long nonblocking = 1;
ioctlsocket(fd, FIONBIO, &nonblocking);

By changing the three functions above, you can port most any application that uses Berkeley sockets to one using Winsock 2. Of course, you mustn't forget to take care of all the Winsock specific stuff like including the libraries, header files, calling WSAStartup, and WSACleanup. If your interested in Winsock 2 you can check it out on MSDN

No comments: