From 6fd96addf4e8caec48f69fed77f11ea1c3b374c2 Mon Sep 17 00:00:00 2001
From: Simon Butcher <simonb@redtangent.net>
Date: Sat, 12 May 2018 18:23:32 +0100
Subject: [PATCH] Change the default IP addresses for DTLS samples

Changes the IP address to bind to for dtls_server.c to be "::" or optionally
"0.0.0.0" if the preprocessor symbol FORCE_IPV4 is defined.

Also changes the destinaton IP address for dtls_client.c to be "::1" or if
FORCE_IPV4 symbol is defined "127.0.0.1".

This change allows on compilation dtls_server.c and dtls_client.c to both be
compiled to use either IPv4 or IPv6 so out of the box they will work together
without problem, and to avoid dtls_server.c binding to IPv6 and dtls_client.c
binding to IPv4.
---
 programs/ssl/dtls_client.c | 11 ++++++++++-
 programs/ssl/dtls_server.c | 11 ++++++++++-
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/programs/ssl/dtls_client.c b/programs/ssl/dtls_client.c
index f271bad30..c29ab34a6 100644
--- a/programs/ssl/dtls_client.c
+++ b/programs/ssl/dtls_client.c
@@ -60,9 +60,18 @@ int main( void )
 #include "mbedtls/certs.h"
 #include "mbedtls/timing.h"
 
+/* Uncomment out the following line to default to IPv4 and disable IPv6 */
+//#define FORCE_IPV4
+
 #define SERVER_PORT "4433"
 #define SERVER_NAME "localhost"
-#define SERVER_ADDR "127.0.0.1" /* forces IPv4 */
+
+#ifdef FORCE_IPV4
+#define SERVER_ADDR "127.0.0.1"     /* Forces IPv4 */
+#else
+#define SERVER_ADDR "::1"
+#endif
+
 #define MESSAGE     "Echo this"
 
 #define READ_TIMEOUT_MS 1000
diff --git a/programs/ssl/dtls_server.c b/programs/ssl/dtls_server.c
index 9d0dda4d1..b4ad6b53a 100644
--- a/programs/ssl/dtls_server.c
+++ b/programs/ssl/dtls_server.c
@@ -34,6 +34,15 @@
 #define mbedtls_time_t     time_t
 #endif
 
+/* Uncomment out the following line to default to IPv4 and disable IPv6 */
+//#define FORCE_IPV4
+
+#ifdef FORCE_IPV4
+#define BIND_IP     "0.0.0.0"     /* Forces IPv4 */
+#else
+#define BIND_IP     "::"
+#endif
+
 #if !defined(MBEDTLS_SSL_SRV_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ||    \
     !defined(MBEDTLS_SSL_COOKIE_C) || !defined(MBEDTLS_NET_C) ||          \
     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) ||        \
@@ -170,7 +179,7 @@ int main( void )
     printf( "  . Bind on udp/*/4433 ..." );
     fflush( stdout );
 
-    if( ( ret = mbedtls_net_bind( &listen_fd, NULL, "4433", MBEDTLS_NET_PROTO_UDP ) ) != 0 )
+    if( ( ret = mbedtls_net_bind( &listen_fd, BIND_IP, "4433", MBEDTLS_NET_PROTO_UDP ) ) != 0 )
     {
         printf( " failed\n  ! mbedtls_net_bind returned %d\n\n", ret );
         goto exit;