From 8b5147c35dadb748a62dca2183ee39866b4c8a69 Mon Sep 17 00:00:00 2001
From: Sergey Fedorov <vital.had@gmail.com>
Date: Fri, 12 Apr 2024 08:23:20 +0800
Subject: [PATCH] Fix for older macOS: include sys/socket.h before net/if.h

Closes: https://github.com/sahlberg/libnfs/issues/455
---
 cmake/ConfigureChecks.cmake | 10 ++++++++--
 include/libnfs-private.h    |  8 ++++----
 2 files changed, 12 insertions(+), 6 deletions(-)

diff --git cmake/ConfigureChecks.cmake cmake/ConfigureChecks.cmake
index c26a02d..3bea395 100644
--- cmake/ConfigureChecks.cmake
+++ cmake/ConfigureChecks.cmake
@@ -1,4 +1,5 @@
 include(CheckIncludeFile)
+include(CheckIncludeFiles)
 check_include_file("arpa/inet.h" HAVE_ARPA_INET_H)
 check_include_file("dispatch/dispatch.h" HAVE_DISPATCH_DISPATCH_H)
 check_include_file("dlfcn.h" HAVE_DLFCN_H)
@@ -8,7 +9,13 @@ check_include_file("memory.h" HAVE_MEMORY_H)
 check_include_file("netdb.h" HAVE_NETDB_H)
 check_include_file("netinet/in.h" HAVE_NETINET_IN_H)
 check_include_file("netinet/tcp.h" HAVE_NETINET_TCP_H)
-check_include_file("net/if.h" HAVE_NET_IF_H)
+check_include_file("sys/socket.h" HAVE_SYS_SOCKET_H)
+# On MacOS 10.8 and earlier, sys/socket.h must be included before net/if.h
+if(HAVE_SYS_SOCKET_H)
+  check_include_files("sys/socket.h;net/if.h" HAVE_NET_IF_H)
+else()
+  check_include_file("net/if.h" HAVE_NET_IF_H)
+endif()
 check_include_file("poll.h" HAVE_POLL_H)
 check_include_file("stdint.h" HAVE_STDINT_H)
 check_include_file("stdlib.h" HAVE_STDLIB_H)
@@ -16,7 +23,6 @@ check_include_file("strings.h" HAVE_STRINGS_H)
 check_include_file("string.h" HAVE_STRING_H)
 check_include_file("sys/filio.h" HAVE_SYS_FILIO_H)
 check_include_file("sys/ioctl.h" HAVE_SYS_IOCTL_H)
-check_include_file("sys/socket.h" HAVE_SYS_SOCKET_H)
 check_include_file("sys/statvfs.h" HAVE_SYS_STATVFS_H)
 check_include_file("sys/stat.h" HAVE_SYS_STAT_H)
 check_include_file("sys/sysmacros.h" HAVE_SYS_SYSMACROS_H)
diff --git include/libnfs-private.h include/libnfs-private.h
index 676fca6..e936d8a 100644
--- include/libnfs-private.h
+++ include/libnfs-private.h
@@ -23,6 +23,10 @@
 #include "config.h"  /* HAVE_SOCKADDR_STORAGE ? */
 #endif
 
+#if !defined(WIN32) && !defined(PS2_EE)
+#include <sys/socket.h>  /* struct sockaddr_storage */
+#endif
+
 #ifdef HAVE_NET_IF_H
 #include <net/if.h>
 #endif
@@ -31,10 +35,6 @@
 #include "lib/krb5-wrapper.h"
 #endif
 
-#if !defined(WIN32) && !defined(PS2_EE)
-#include <sys/socket.h>  /* struct sockaddr_storage */
-#endif
-
 #if defined(WIN32) && !defined(IFNAMSIZ)
 #define IFNAMSIZ 255
 #endif
