03_resolve-port-names.diff
[paraslash.git] / net.c
diff --git a/net.c b/net.c
index 126b51400a677a98d431e38214c82451a22f63fc..6ab96215df880dc04eea0f6f90c48fd385720816 100644 (file)
--- a/net.c
+++ b/net.c
@@ -187,6 +187,31 @@ failed:
        return NULL;
 }
 
+/**
+ * Stringify port number, resolve into service name where defined.
+ * \param port 2-byte port number, in host-byte-order.
+ * \param transport Transport protocol name (e.g. "udp", "tcp"), or NULL.
+ * \return Pointer to static result buffer.
+ *
+ * \sa getservent(3), services(5), nsswitch.conf(5)
+ */
+const char *stringify_port(int port, const char *transport)
+{
+       static char service[NI_MAXSERV];
+
+       if (port < 0 || port > 0xFFFF) {
+               snprintf(service, sizeof(service), "undefined (%d)", port);
+       } else {
+               struct servent *se = getservbyport(htons(port), transport);
+
+               if (se == NULL)
+                       snprintf(service, sizeof(service), "%u", port);
+               else
+                       snprintf(service, sizeof(service), "%s", se->s_name);
+       }
+       return service;
+}
+
 /**
  * Determine the socket type for a given layer-4 protocol.
  *
@@ -412,7 +437,7 @@ normalize_ip_address(const struct sockaddr_storage *ss)
  *
  * \param sa The IPv4/IPv6 socket address to use.
  *
- * \sa getnameinfo(3).
+ * \sa getnameinfo(3), services(5), nsswitch.conf(5)
  */
 static char *host_and_port(const struct sockaddr_storage *ss)
 {
@@ -424,7 +449,7 @@ static char *host_and_port(const struct sockaddr_storage *ss)
        ret = getnameinfo(sa, salen(sa),
                          hbuf, sizeof(hbuf),
                          sbuf, sizeof(sbuf),
-                         NI_NUMERICHOST | NI_NUMERICSERV);
+                         NI_NUMERICHOST);
        if (ret == 0) {
                snprintf(output, sizeof(output), "%s#%s", hbuf, sbuf);
        } else {