--- netutils.c-orig	2005-10-31 13:03:19.000000000 -0700
+++ netutils.c	2006-10-02 15:59:13.768711279 -0600
@@ -70,7 +70,7 @@
 	fd_set readfds;
 	int recv_length = 0;
 
-	result = np_net_connect (server_address, server_port, &sd, IPPROTO_TCP);
+	result = np_net_connect (server_address, server_port, &sd, IPPROTO_TCP, NULL);
 	if (result != STATE_OK)
 		return STATE_CRITICAL;
 
@@ -145,7 +145,7 @@
 
 	result = STATE_OK;
 
-	result = np_net_connect (server_address, server_port, &sd, proto);
+	result = np_net_connect (server_address, server_port, &sd, proto, NULL);
 	if (result != STATE_OK)
 		return STATE_CRITICAL;
 
@@ -159,10 +159,10 @@
 
 /* opens a tcp or udp connection to a remote host or local socket */
 int
-np_net_connect (const char *host_name, int port, int *sd, int proto)
+np_net_connect (const char *host_name, int port, int *sd, int proto, const char *src_ip)
 {
 	struct addrinfo hints;
-	struct addrinfo *r, *res;
+	struct addrinfo *r, *res, *src;
 	struct sockaddr_un su;
 	char port_str[6];
 	int socktype, result;
@@ -177,10 +177,24 @@
 		hints.ai_socktype = socktype;
 
 		snprintf (port_str, sizeof (port_str), "%d", port);
+
+		/* Get address info of source interface */
+		if (src_ip)
+		{
+			result = getaddrinfo (src_ip, "0", &hints, &src);
+
+			if (result != 0) {
+				printf ("Invalid source address = %s port = INADDR_ANY: %s\n", src_ip, gai_strerror (result));
+				return STATE_UNKNOWN;
+			}
+		}
+
+		/* Resolve destination address */
 		result = getaddrinfo (host_name, port_str, &hints, &res);
 
 		if (result != 0) {
 			printf ("%s\n", gai_strerror (result));
+			if (src_ip) freeaddrinfo (src);
 			return STATE_UNKNOWN;
 		}
 
@@ -192,9 +206,25 @@
 			if (*sd < 0) {
 				printf (_("Socket creation failed\n"));
 				freeaddrinfo (r);
+				if (src_ip) freeaddrinfo (src);
 				return STATE_UNKNOWN;
 			}
 
+			/* Bind to a specific local interface, if specified */
+			if (src_ip)
+			{
+				result = bind (*sd, src->ai_addr, src->ai_addrlen);
+
+				if (result < 0) {
+#ifdef EADDRNOTAVAIL
+					/* SVr4 defines EADDRNOTAVAIL. Many systems have it, so check for it */
+					if (errno == EADDRNOTAVAIL)
+						die(STATE_UNKNOWN, "Can't send from source-ip %s. No interface has that address\n", src_ip);
+#endif
+					die(STATE_UNKNOWN, "Unable to bind source address %s: %s\n", src_ip, strerror(errno));
+				}
+			}
+
 			/* attempt to open a connection */
 			result = connect (*sd, r->ai_addr, r->ai_addrlen);
 
@@ -208,6 +238,9 @@
 				case ECONNREFUSED:
 					was_refused = TRUE;
 					break;
+				case EINVAL:
+					if (src_ip)
+						die(STATE_UNKNOWN, "Can't send to %s through interface with address %s\n", inet_ntoa(((struct sockaddr_in *)(r->ai_addr))->sin_addr), src_ip);
 				}
 			}
 
@@ -215,6 +248,7 @@
 			r = r->ai_next;
 		}
 		freeaddrinfo (res);
+		if (src_ip) freeaddrinfo (src);
 	} 
 	/* else the hostname is interpreted as a path to a unix socket */
 	else {