Browse Source

more documentation for port binder

Fabio Arnold 9 years ago
parent
commit
71ad0a727e
1 changed files with 17 additions and 5 deletions
  1. 17 5
      native/bind.c

+ 17 - 5
native/bind.c

@@ -11,11 +11,15 @@
 
 #define CONTROLLEN CMSG_LEN(sizeof(int))
 
-#define UNIX_PATH "hostage"
+// LocalSocket uses the Linux abstract namespace instead of the filesystem.
+// In C these addresses are specified by prepending '\0' to the path.
+// http://stackoverflow.com/questions/14643571/localsocket-communication-with-unix-domain-in-android-ndk
+#define UNIX_PATH "\0hostage"
 
 #define TCP "TCP"
 #define UDP "UDP"
 
+// create unix domain local socket for inter process communication
 int ipc_sock() {
 	int fd;
 	struct sockaddr_un addr;
@@ -25,11 +29,15 @@ int ipc_sock() {
 		return -1;
 	}
 
-	memset(&addr, 0, sizeof(addr));
+	// Also note that you should not pass sizeof(sockaddr_un) to bind or connect because all bytes
+	// following the '\0' character are interpreted as the abstract socket name. Calculate and pass
+	// the real size instead
 	addr.sun_family = AF_UNIX;
-	strncpy(&addr.sun_path[1], UNIX_PATH, strlen(UNIX_PATH));
+	int addrsize = strlen(&(UNIX_PATH)[1]) + 1;
+	memcpy(addr.sun_path, UNIX_PATH, addrsize);
 
-	if (connect(fd, (struct sockaddr*) &addr, sizeof(sa_family_t) + strlen(UNIX_PATH) + 1) == -1) {
+	addrsize += sizeof(addr.sun_family); // total size
+	if (connect(fd, (struct sockaddr*)&addr, addrsize) == -1) {
 		perror("Unable to connect local socket");
 		return -1;
 	}
@@ -72,6 +80,7 @@ int net_sock(int type, int port) {
 	return fd;
 }
 
+// send a file descriptor via inter process communication
 int send_fd(int fd, int fd_to_send) {
 	struct iovec iov[1];
 	struct cmsghdr *cmptr;
@@ -107,6 +116,8 @@ int main(int argc, char *argv[]) {
 	int ipc_fd, net_fd;
 
 	if (argc < 3) {
+		printf("usage: %s <protocol> <port>\n", argv[0]);
+		printf("where protocol is either TCP or UDP and port is between 1 and 65535\n");
 		exit(EXIT_FAILURE);
 	}
 
@@ -118,7 +129,8 @@ int main(int argc, char *argv[]) {
 		exit(EXIT_FAILURE);
 	}
 
-	if ((port = atoi(argv[2])) < 1 || (port = atoi(argv[2])) > 65535) {
+	port = atoi(argv[2]);
+	if (!(port >= 0 && port <= 65535)) {
 		exit(EXIT_FAILURE);
 	}