From 16eac315358e79e919c82cdaf3bb7be6ccf35e83 Mon Sep 17 00:00:00 2001
From: "Christian W. Zuckschwerdt" <christian@zuckschwerdt.org>
Date: Fri, 22 Mar 2019 17:51:30 +0100
Subject: [PATCH] Fix IPv6 connect in mg_socket_if_connect_tcp

---
 src/mg_net_if_socket.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/mg_net_if_socket.c b/src/mg_net_if_socket.c
index 607e2b53..51c0788f 100644
--- a/src/mg_net_if_socket.c
+++ b/src/mg_net_if_socket.c
@@ -37,7 +37,7 @@ static int mg_is_error(void) {
 void mg_socket_if_connect_tcp(struct mg_connection *nc,
                               const union socket_address *sa) {
   int rc, proto = 0;
-  nc->sock = socket(AF_INET, SOCK_STREAM, proto);
+  nc->sock = socket(sa->sa.sa_family, SOCK_STREAM, proto);
   if (nc->sock == INVALID_SOCKET) {
     nc->err = mg_get_errno() ? mg_get_errno() : 1;
     return;
@@ -45,7 +45,9 @@ void mg_socket_if_connect_tcp(struct mg_connection *nc,
 #if !defined(MG_ESP8266)
   mg_set_non_blocking_mode(nc->sock);
 #endif
-  rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
+  socklen_t sa_len =
+      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
+  rc = connect(nc->sock, &sa->sa, sa_len);
   nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
   DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
        nc->err));
