--- tclIOSock.c.orig	Mon Jul 29 12:54:41 2002
+++ tclIOSock.c	Fri Nov 24 17:50:43 2006
@@ -41,23 +41,44 @@
     char *proto;		/* "tcp" or "udp", typically */
     int *portPtr;		/* Return port number */
 {
-    struct servent *sp;		/* Protocol info for named services */
-    Tcl_DString ds;
-    CONST char *native;
+#ifdef HAVE_GETSERVBYNAME_R
+        if (Tcl_GetInt(NULL, string, portPtr) != TCL_OK) {
+		/*
+		 * Don't bother translating 'proto' to native.
+		 */
+                struct servent se;      /* Protocol info for named services */
+                struct servent_data sd; /* Opaque structure used by getserven_r */
+                Tcl_DString name;
 
-    if (Tcl_GetInt(NULL, string, portPtr) != TCL_OK) {
-	/*
-	 * Don't bother translating 'proto' to native.
-	 */
-	 
-	native = Tcl_UtfToExternalDString(NULL, string, -1, &ds);
-	sp = getservbyname(native, proto);		/* INTL: Native. */
-	Tcl_DStringFree(&ds);
-	if (sp != NULL) {
-	    *portPtr = ntohs((unsigned short) sp->s_port);
-	    return TCL_OK;
-	}
-    }
+                Tcl_DStringInit(&name);
+                Tcl_UtfToExternalDString(NULL, string, -1, &name);
+                /* sd needs to be initialized, se does not */
+                (void) memset((void *) &sd, 0, sizeof(sd));
+                if (getservbyname_r((const char *) Tcl_DStringValue(&name), proto, &se, &sd) == 0) {
+                        *portPtr = ntohs((unsigned short) se.s_port);
+                        Tcl_DStringFree(&name);
+                        return TCL_OK;
+                }
+                Tcl_DStringFree(&name);
+        }
+#else
+        if (Tcl_GetInt(NULL, string, portPtr) != TCL_OK) {
+		/*
+		 * Don't bother translating 'proto' to native.
+		 */
+                struct servent *sep;    /* Protocol info for named services */
+                Tcl_DString name;
+
+                Tcl_DStringInit(&name);
+                Tcl_UtfToExternalDString(NULL, string, -1, &name);
+                sep = getservbyname((const char *) Tcl_DStringValue(&name), proto);		/* INTL: Native. */
+                Tcl_DStringFree(&name);
+                if (sep != NULL) {
+                        *portPtr = ntohs((unsigned short) sep->s_port);
+                        return TCL_OK;
+                }
+        }
+#endif /* HAVE_GETSERVBYNAME_R */
     if (Tcl_GetInt(interp, string, portPtr) != TCL_OK) {
 	return TCL_ERROR;
     }
