socket bug in mlton 20000906

Doug Bagley doug@bagley.org
07 Jun 2001 17:55:01 -0500


Hi Stephen,

Someone submitted an echo client/server solution to my shootout,
and when I had problems running it due to a run-time assertion on
setsockopt, I found what looks like a bug in mlton-lib.c.

The setsockopt(SO_REUSEADDR) should be located between calls to
socket() and bind() on the listen socket, not after a new client
socket is accept()'ed.

I imagine you may have already found this one, but enclosed is a patch
in the off chance you have not.

I've tested the following patch, and it works for me.  You may want to
adjust it (like the error message). 

Thanks.

Cheers,
Doug

*** /home/doug/langs/tmp/mlton-20000906/src/runtime/mlton-lib.c	Fri Oct 20 00:51:29 2000
--- /home/doug/langs/mlton-20000906/src/runtime/mlton-lib.c	Thu Jun  7 17:40:04 2001
***************
*** 700,710 ****
--- 700,713 ----
  	int 			sl, len;
  	int *port;
  	int *resultSocket;
+ 	int optval = 1;
  
  	port = (int*)portp;
  	resultSocket = (int*)resultSocketp;
  	sl = socket(AF_INET, SOCK_STREAM, 0);
  	if (sl < 0) return -1;
+ 	if (setsockopt(sl, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1)
+ 	    die("Socket_listen/setsockopt");
  	addr.sin_family = AF_INET;
  	addr.sin_addr.s_addr = htonl(INADDR_ANY);
  	addr.sin_port = htons(*port);
***************
*** 769,778 ****
  	yes = TRUE;
  	len = sizeof(sockaddr_in);
  	fd = accept(sl, &sockaddr_in, &len);
- 	if (fd >= 0)
- 		unless (0 == setsockopt(fd, IPPROTO_TCP, SO_REUSEADDR, &yes, 
- 					sizeof(yes)))
- 			die("setsockopt SO_REUSEADDR failed");
  	assert(sockaddr_in.sin_family == AF_INET);
  	return fd;
  }
--- 772,777 ----