Subject: Re: MinGW port usable

From: "H. Peter Anvin" <[email-masked]>
Date: Fri, 02 Feb 2007 00:55:38 -0800

H. Peter Anvin wrote:
> H. Peter Anvin wrote:
>>
>> Except they are (for NT-based Windows), so you're doing something 
>> goofy.  This is a widely used construct, so it can't be that broken.
>>
> 
> Erf... I dug through this, and it seems that WriteFile only works on a 
> socket if it has an OVERLAPPED argument now, because the socket is 
> opened for overlapping I/O.  This must be new behaviour in XP-SP2, 
> because this definitely wasn't the case when I last played with this 
> stuff back in 2003.  The Internet is full of people using this 
> technique, but I haven't found a way to get a socket which is *not* 
> opened for overlapping I/O.
> 
> How typical of Microsoft to break an incredibly powerful unified 
> paradigm, sort-of repair it, and then break it again.  There doesn't 
> seem to be an obvious way to repair this, either, since MS DLLs won't 
> let you override for example the write() function as called from inside 
> the C runtime DLL.
> 
> "Some people are just a total waste of carbon..."
> 

**HAH***

I found a workaround after all.  The trick is to use WSASocket() with a 
last argument 0 instead of socket().

I feel dirty now...

#include <winsock2.h>
#include <fcntl.h>
#include <io.h>

#define socket(a,b,c) sane_socket(a,b,c)

int sane_socket(int domain, int type, int protocol)
{
	SOCKET s;
	int fd;

	s = WSASocket(domain, type, protocol, NULL, 0, 0);
	if (s == INVALID_SOCKET) {
		/*
		 * WSAGetLastError() values seem to be mostly
		 * errno+10000; verify this or replace this with
		 * a switch statement...
		 */
		errno = WSAGetLastError() - 10000;
		return -1;
	}
	
	fd = _open_osfhandle(s, 0);
	if (fd < 0)
		closesocket(s);

	return fd;
}