Porting Winsock to Linux Sockets

2020-03-13 16:15发布

问题:

I have a program that does some networking using Winsock, and one of our requirements right now is to port over our program to Linux. The only thing stopping us from doing this is Winsock.

My question is: How easy can I port this over to a Linux implementation?

Are there any pitfalls I should be aware of, and if I simply include the appropriate header files, what sort of things will I have to be sure to handle?

Thanks for any help!

I'd post code but I can't unfortunately due to legal reasons. But, our code does use the following:

WSAStartup(..)
WSACleanup(..)
Socket(..)
sendto(..)
recvfrom(..)
ioctlsocket(..)
setsocketopt(..)

回答1:

It will depend if you use any windows specific networking functionality or if you're just using mostly the mostly BSD compatible API.

So, if you're using overlapped I/O and I/O completion ports and other advanced parts of the Winsock API then things will be very difficult to port and if you're just using the BSD compatible stuff then it should be easy to write a thin translation layer or even just have the winsock startup and shutdown stuff inside a windows specific ifdef...

This may help: http://tangentsoft.net/wskfaq/articles/bsd-compatibility.html



回答2:

Based on that list of functions, things should more or less just work. Add #if _WIN32 around the calls to WSAStartup and WSACleanup (the linux equivalent is to not do anything, the sockets library is initialized automatically).

You also might need some OS-dependent code when setting socket options, some of them are the same, some aren't, and the types might be different.



回答3:

The only calls that make porting difficult are the WSA* calls.

WSAStartup() -> nop WSACleanup() -> nop

Socket/setsockopt -> socket/setsockopt

Under *nix, sockets are blocking by default and it's not necessary or possible to use that weird setsockopt call to fiddle with it.

ioctlsocket -> ioctl

Under *nix we don't like asynchronous sockets much and prefer to use the select() system call.

---- Rest of this answer seems only to apply to Win95 compatible winsock ----

Unfortunately as the original socket() in Winsock was broken in some cases, you probably used WSASocket() and so have to convert those calls.



回答4:

Without seeing code, it's tough to say how easy it is. But you should be able to replace winsock calls to analogs in sys/sockets.h.