/********************************************************************\ Generic example for remote control via a socket interface Oliver Grimm, March 2009 \********************************************************************/ #include #include #include #include #define MAX_COM_SIZE 10000 int main(int argc, char *argv[]) { char Buffer[MAX_COM_SIZE],ServerName[MAX_COM_SIZE]="eth-vme02"; int SocketDescriptor, DAQPort = 2000; struct sockaddr_in SocketAddress; fd_set ReadFileDescriptor; printf("+++ Command line socket interface +++\n"); if (argc != 3) { printf("Usage: %s \n", argv[0]); printf("Taking defaults: <%s> <%d>\n", ServerName, DAQPort); } else { sprintf(ServerName,argv[1]); DAQPort = atoi(argv[2]); } // Open socket descriptor if ((SocketDescriptor = socket(PF_INET, SOCK_STREAM, 0)) == -1) { printf("Error: Could not open socket."); exit(EXIT_FAILURE); } // Resolve hostname and try to connect to server struct hostent *hostent = gethostbyname(ServerName); if (hostent==0) { printf("\nCould not resolve host name.\n"); close(SocketDescriptor); exit(EXIT_FAILURE); } SocketAddress.sin_family = PF_INET; SocketAddress.sin_port = htons((unsigned short) DAQPort); SocketAddress.sin_addr = *(struct in_addr*) hostent->h_addr; if (connect(SocketDescriptor, (struct sockaddr *) &SocketAddress, sizeof(SocketAddress))==-1) { printf("Error: Could not connect to server %s (port %d)\n", ServerName, DAQPort); close(SocketDescriptor); exit(EXIT_FAILURE); } printf("\nConnected to %s (port %d).\n" "Type 'exit' to quit.\n", ServerName, DAQPort); signal(SIGPIPE,SIG_IGN); // Do not kill process if writing to closed socket while(true) { printf("> "); fflush(stdout); // Wait for data either from terminal (stdin) or from socket FD_ZERO(&ReadFileDescriptor); FD_SET(SocketDescriptor, &ReadFileDescriptor); FD_SET(STDIN_FILENO, &ReadFileDescriptor); if (select(((int) SocketDescriptor)+1, &ReadFileDescriptor, NULL, NULL, NULL)==-1) { perror("Error with select()"); break; } memset(Buffer, 0, sizeof(Buffer)); if (FD_ISSET(STDIN_FILENO, &ReadFileDescriptor)) { // Data from stdin fgets(Buffer, MAX_COM_SIZE, stdin); if (!strcmp(Buffer,"exit\n")) break; if ((write(SocketDescriptor, Buffer, strlen(Buffer)))<1) // Write command to socket printf("Error: Could not write command to socket.\n"); } else if (FD_ISSET(SocketDescriptor, &ReadFileDescriptor)) { // Data from socket memset(Buffer, 0, sizeof(Buffer)); if(read(SocketDescriptor, Buffer, MAX_COM_SIZE)==0) { printf("Server not exisiting anymore, exiting...\n"); break; } printf("\r%s", Buffer); } } // Close socket descriptor if (!close(SocketDescriptor)) printf("Connection to %s closed.\n", ServerName); exit(EXIT_SUCCESS); }