Add getNetworkForSocket().

This doesn't require a roundtrip to netd, since anybody can read the SO_MARK.

Change-Id: I51dd17725c4534cb0d5dbc8e93e844e6a7847959
diff --git a/client/NetdClient.cpp b/client/NetdClient.cpp
index 8a54354..7380224 100644
--- a/client/NetdClient.cpp
+++ b/client/NetdClient.cpp
@@ -16,6 +16,7 @@
 
 #include "NetdClient.h"
 
+#include "Fwmark.h"
 #include "FwmarkClient.h"
 #include "FwmarkCommand.h"
 #include "resolv_netid.h"
@@ -163,6 +164,19 @@
     }
 }
 
+extern "C" int getNetworkForSocket(unsigned* netId, int socketFd) {
+    if (!netId || socketFd < 0) {
+        return EBADF;
+    }
+    Fwmark fwmark;
+    socklen_t fwmarkLen = sizeof(fwmark.intValue);
+    if (getsockopt(socketFd, SOL_SOCKET, SO_MARK, &fwmark.intValue, &fwmarkLen) == -1) {
+        return errno;
+    }
+    *netId = fwmark.netId;
+    return 0;
+}
+
 extern "C" unsigned getNetworkForProcess() {
     return netIdForProcess;
 }
diff --git a/server/Fwmark.h b/include/Fwmark.h
similarity index 92%
rename from server/Fwmark.h
rename to include/Fwmark.h
index cb2900f..7360e1b 100644
--- a/server/Fwmark.h
+++ b/include/Fwmark.h
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#ifndef NETD_SERVER_FWMARK_H
-#define NETD_SERVER_FWMARK_H
+#ifndef NETD_INCLUDE_FWMARK_H
+#define NETD_INCLUDE_FWMARK_H
 
 #include "Permission.h"
 
@@ -39,4 +39,4 @@
 
 static_assert(sizeof(Fwmark) == sizeof(uint32_t), "The entire fwmark must fit into 32 bits");
 
-#endif  // NETD_SERVER_FWMARK_H
+#endif  // NETD_INCLUDE_FWMARK_H
diff --git a/include/NetdClient.h b/include/NetdClient.h
index 0b75d13..1a2f8be 100644
--- a/include/NetdClient.h
+++ b/include/NetdClient.h
@@ -24,6 +24,7 @@
 
 // All functions below that return an int return 0 on success or an errno value on failure.
 
+int getNetworkForSocket(unsigned* netId, int socketFd);
 int setNetworkForSocket(unsigned netId, int socketFd);
 
 unsigned getNetworkForProcess(void);
diff --git a/server/Permission.h b/include/Permission.h
similarity index 93%
rename from server/Permission.h
rename to include/Permission.h
index 38f946b..1d0ff8d 100644
--- a/server/Permission.h
+++ b/include/Permission.h
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#ifndef NETD_SERVER_PERMISSION_H
-#define NETD_SERVER_PERMISSION_H
+#ifndef NETD_INCLUDE_PERMISSION_H
+#define NETD_INCLUDE_PERMISSION_H
 
 // This enum represents the permissions we care about for networking. When applied to an app, it's
 // the permission the app (UID) has been granted. When applied to a network, it's the permission an
@@ -37,4 +37,4 @@
 
 Permission permissionFromString(const char* permission);
 
-#endif  // NETD_SERVER_PERMISSION_H
+#endif  // NETD_INCLUDE_PERMISSION_H