--- src/interfaces/libpq/fe-connect.c~	2009-06-11 15:49:13.000000000 +0100
+++ src/interfaces/libpq/fe-connect.c	2009-09-24 20:48:53.000000000 +0100
@@ -817,7 +817,16 @@
 
 	/* Set up port number as a string */
 	if (conn->pgport != NULL && conn->pgport[0] != '\0')
+	{
 		portnum = atoi(conn->pgport);
+		if (portnum < 1 || portnum > 65535)
+		{
+			appendPQExpBuffer(&conn->errorMessage,
+							  libpq_gettext("invalid port number \"%s\" specified\n"),
+							  conn->pgport);
+			goto connect_errReturn;
+		}
+	}
 	else
 		portnum = DEF_PGPORT;
 	snprintf(portstr, sizeof(portstr), "%d", portnum);
