@@ -1513,11 +1513,12 @@ nc_connect_unix(const char *address, struct ly_ctx *ctx)
15131513 *
15141514 * @param[in] saddr Sockaddr to convert.
15151515 * @param[out] str_ip String IP address.
1516+ * @param[out] port Optional port.
15161517 * @return 0 on success.
15171518 * @return -1 on error.
15181519 */
15191520static int
1520- nc_saddr2str (const struct sockaddr * saddr , char * * str_ip )
1521+ nc_saddr2str (const struct sockaddr * saddr , char * * str_ip , uint16_t * port )
15211522{
15221523 void * addr ;
15231524 socklen_t str_len ;
@@ -1533,8 +1534,14 @@ nc_saddr2str(const struct sockaddr *saddr, char **str_ip)
15331534
15341535 if (saddr -> sa_family == AF_INET ) {
15351536 addr = & ((struct sockaddr_in * )saddr )-> sin_addr ;
1537+ if (port ) {
1538+ * port = ntohs (((struct sockaddr_in * )saddr )-> sin_port );
1539+ }
15361540 } else {
15371541 addr = & ((struct sockaddr_in6 * )saddr )-> sin6_addr ;
1542+ if (port ) {
1543+ * port = ntohs (((struct sockaddr_in6 * )saddr )-> sin6_port );
1544+ }
15381545 }
15391546 if (!inet_ntop (saddr -> sa_family , addr , * str_ip , str_len )) {
15401547 ERR (NULL , "Converting host to IP address failed (%s)." , strerror (errno ));
@@ -1571,14 +1578,9 @@ sock_connect(int timeout_ms, int *sock_pending, struct addrinfo *res, struct nc_
15711578 sock = * sock_pending ;
15721579 } else {
15731580 assert (res );
1574- if (nc_saddr2str (res -> ai_addr , & str )) {
1581+ if (nc_saddr2str (res -> ai_addr , & str , & port )) {
15751582 return -1 ;
15761583 }
1577- if (res -> ai_family == AF_INET6 ) {
1578- port = ntohs (((struct sockaddr_in6 * )res -> ai_addr )-> sin6_port );
1579- } else {
1580- port = ntohs (((struct sockaddr_in * )res -> ai_addr )-> sin_port );
1581- }
15821584 VRB (NULL , "Trying to connect via %s to %s:%u." , (res -> ai_family == AF_INET6 ) ? "IPv6" : "IPv4" , str , port );
15831585 free (str );
15841586
@@ -1707,7 +1709,7 @@ nc_sock_connect(const char *host, uint16_t port, int timeout_ms, struct nc_keepa
17071709 goto error ;
17081710 }
17091711
1710- if (nc_saddr2str (res -> ai_addr , ip_host )) {
1712+ if (nc_saddr2str (res -> ai_addr , ip_host , NULL )) {
17111713 goto error ;
17121714 }
17131715 break ;
@@ -1725,7 +1727,7 @@ nc_sock_connect(const char *host, uint16_t port, int timeout_ms, struct nc_keepa
17251727 goto error ;
17261728 }
17271729
1728- if (nc_saddr2str ((struct sockaddr * )& saddr , ip_host )) {
1730+ if (nc_saddr2str ((struct sockaddr * )& saddr , ip_host , NULL )) {
17291731 goto error ;
17301732 }
17311733 }
0 commit comments