problem with sockets under win32; premature connection termination

Regan Heath regan at netmail.co.nz
Sat May 12 08:36:18 PDT 2007


I'd like to think I have a bit of experience with sockets and yet this problem has me a bit stumped too.  I decided to pull the calls to the winsock stuff out of the classes and call them directly, eg

---------------------
import std.stdio, std.socket, std.string, std.file;

import std.c.windows.winsock, std.windows.syserror, std.c.windows.windows;

alias std.c.windows.winsock ws;

void main(char[][] args) {
	char[] buf = "TEST";
	socket_t l, request;
	sockaddr_in sin;	
	uint num = 0;
	int size;
	
	sin.sin_addr.s_addr = inet_addr("127.0.0.1");
	sin.sin_port = htons(atoi(args[1]));
	writef(std.string.toString(inet_ntoa(sin.sin_addr)),":",
		std.string.toString(ntohs(sin.sin_port)),"\n");
	
	l = cast(socket_t)ws.socket(AddressFamily.INET, SocketType.STREAM, ProtocolType.TCP);
	writef(l,"\n");
	writef(ws.ioctlsocket(l, FIONBIO, &num),"\n");
	writef(ws.bind(l, cast(sockaddr*)&sin, sin.sizeof),"\n");
	writef(ws.listen(l, 16),"\n");

	request = cast(socket_t) ws.accept(l, null, null);

	size = sin.sizeof;
	ws.getsockname(request, cast(sockaddr*)&sin, &size);
	writef(std.string.toString(inet_ntoa(sin.sin_addr)),":",
		std.string.toString(ntohs(sin.sin_port)),"\n");

	writef(request,"\n");
	writef(ws.ioctlsocket(request, FIONBIO, &num),"\n");
	writef(ws.send(request, buf.ptr, buf.length, 0),"\n");
	Sleep(5000);
	writef(ws.shutdown(request, SocketShutdown.BOTH),"\n");
	writef(ws.closesocket(request),"\n");
	writef(ws.closesocket(l),"\n");
}
---------------------

Compiling this with:

  dmd bug.d wsock32.lib

and running with:

  bug 80

then telnetting to it, i.e.

  telnet 127.0.0.1 80

gives me this output on screen:

127.0.0.1:80
924
0
0
0
127.0.0.1:80
916
0
4
0
0
0

the actual socket handle values may differ for you but note the send reports 4 and the other calls report 0, no error.

The most interesting part is the pause I added, this prevent the socket being closed immediately, however my telnet session connects and immediately closes receiving no data.

I'm hoping by posting this someone can tell us both where we went wrong ;)

Regan Heath



More information about the Digitalmars-d mailing list