+/* nothing sophisticated: set up a listening socket
+ */
+int setup_socket()
+{
+ int listenfd = 0;
+ struct sockaddr_in serv_addr;
+
+ listenfd = socket(AF_INET, SOCK_STREAM, 0);
+ memset(&serv_addr, '0', sizeof(serv_addr));
+
+ serv_addr.sin_family = AF_INET;
+ serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
+ serv_addr.sin_port = htons(5000);
+
+ bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
+ listen(listenfd, 1);
+
+ return listenfd;
+}
+
+/* sees if there is an incoming connection (non-blocking). if so,
+ accept it and return it
+ */
+int get_connection(int listenfd)
+{
+ int connfd = 0;
+ int flag = 1;
+ int status;
+ fd_set active_fd_set;
+
+ struct timeval tv;
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 1;
+
+ /* Initialize the set of active sockets. */
+ FD_ZERO (&active_fd_set);
+ FD_SET (listenfd, &active_fd_set);
+
+ /* Block until input arrives on one or more active sockets. */
+ status = select (FD_SETSIZE, &active_fd_set, NULL, NULL, &tv);
+ switch (status)
+ {
+ case -1:
+ printf("Error listening on socket\n");
+ exit(status); // error
+ return -1;
+ case 0:
+ return -1; // timeout (nothing read)
+ default:
+ // return accepted socket
+ connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
+ setsockopt(connfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag,
+ sizeof(int));
+ return connfd;
+ }
+}
+