[vlc-devel] [PATCH 6/7] mdns: Add basic ip address detection (Linux)

Roland Bewick roland.bewick at gmail.com
Wed Jul 24 17:43:49 CEST 2019


---
 modules/services_discovery/microdns.c | 62 +++++++++++++++++++++++++++++++++--
 1 file changed, 59 insertions(+), 3 deletions(-)

diff --git a/modules/services_discovery/microdns.c b/modules/services_discovery/microdns.c
index c460126b58..fa34ffa8d8 100644
--- a/modules/services_discovery/microdns.c
+++ b/modules/services_discovery/microdns.c
@@ -28,6 +28,12 @@
 #include <stdatomic.h>
 #include <assert.h>
 
+#if defined( _WIN32 )
+
+#else
+    #include <ifaddrs.h>
+#endif
+
 #include <vlc_common.h>
 #include <vlc_plugin.h>
 #include <vlc_modules.h>
@@ -868,9 +874,59 @@ CloseRD( vlc_object_t *p_this )
     CleanDiscoveryCommon( p_sys );
 }
 
-static char * detect_ip_address()
+static char * detect_ip_address( vlc_object_t *p_obj )
 {
-    return strdup("127.0.0.1"); /* TODO: actually detect ip address */
+    char result[16] = "127.0.0.1";
+    bool found = false;
+#if defined( _WIN32 )
+
+#else
+    struct ifaddrs *id;
+    if( getifaddrs( &id ) == 0 )
+    {
+        int selected_priority = 0;
+
+        for( ; id != NULL; id = id->ifa_next )
+        {
+            if( id->ifa_addr->sa_family == AF_INET )
+            {
+                struct sockaddr_in *addr_in = (struct sockaddr_in *)id->ifa_addr;
+                
+                char *ip_address = inet_ntoa( addr_in->sin_addr );
+
+                /* TODO: smarter priority function. */
+                int priority = 0;
+                if( strncmp( "eth0", id->ifa_name, strlen( "eth0" ) ) == 0 )
+                {
+                    priority = 1000;
+                }
+                else if( strncmp( "wifi0", id->ifa_name, strlen( "wifi0" ) ) == 0 )
+                {
+                    priority = 2000;
+                }
+
+                msg_Dbg( p_obj, "Assigned interface %s priority %d",
+                         id->ifa_name, priority);
+
+                if( priority > selected_priority )
+                {
+                    strcpy( result, ip_address );
+                    selected_priority = priority;
+                    found = true;
+                }
+            }
+        }
+    }
+    else
+    {
+        msg_Err( p_obj, "Couldn't get interface addresses");
+    }
+#endif
+
+    if ( !found )
+        msg_Err( p_obj, "No interface address found");
+
+    return strdup(result);
 }
 
 static int
@@ -901,7 +957,7 @@ OpenSA( vlc_object_t *p_obj )
     if( !p_sys->psz_http_host )
     {
         msg_Dbg( p_obj, "http-host unset, detecting local IP address...");
-        p_sys->psz_http_host = detect_ip_address();
+        p_sys->psz_http_host = detect_ip_address( p_obj );
         msg_Dbg( p_obj, "chose local IP address: %s", p_sys->psz_http_host);
     }
 
-- 
2.11.0



More information about the vlc-devel mailing list