#include #include #include #include #include // this program expects the server address as a parameter void main(int argc, char *argv[]) { int s, // the socket handle rc; // return code char szBuf[256]; // data buffer struct sockaddr_in server; // server address if (argc != 2) { cerr << "Error! Incorrect number of arguments." << endl; return; } s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { cerr << "Error! Cannot create socket." << endl; return; } bzero(&server, sizeof(struct sockaddr_in); server.sin_family = AF_INET; server.sin_port = htons(7777); server.sin_addr = inet_addr(argv[1]); // use command line address rc = connect(s, (struct sockaddr *) &server, sizeof(struct sockaddr_in)); if (rc < 0) { cerr << "Error! Connect failed." << endl; return; } // do some processing of data between client and server strcpy(szBuf, "HELLO\r\n"); rc = send(s, szBuf, strlen(szBuf), 0); if (rc < 0) { cerr << "Error! Send failed." << endl; return; } rc = RecvLine(s, szBuf, 256); if (rc < 0) { cerr << "Error! RecvLine failed." << endl; return; } if (strcmp(szBuf, "OK") != 0) { cerr << "Error! Unknown reply from server." << endl; return; } strcpy(szBuf, "GOODBYE\r\n"); rc = send(s, szBuf, strlen(szBuf), 0); if (rc < 0) { cerr << "Error! Send failed." << endl; return; } rc = RecvLine(s, szBuf, 256); if (rc < 0) { cerr << "Error! RecvLine failed." << endl; return; } if (strcmp(szBuf, "OK") != 0) { cerr << "Error! Unknown reply from server." << endl; return; } close(s); } // ---------------------------------------------------------------- // Receive a command line terminated by a telnet eol sequence int RecvLine(int iSocket, char *szBuf, int iLen) { int iBytesRead, iIdx, bNotDone; iBytesRead = recv(iSocket, &szBuf[0], 1, 0); iIdx = 1; bNotDone = TRUE; while (bNotDone == TRUE) { iBytesRead = recv(iSocket, &szBuf[iIdx], 1, 0); if (iBytesRead < 0) { return ( -1 ); // error receiving } iIdx++; if ( (szBuf[iIdx - 2] == '\r') && (szBuf[iIdx – 1] == '\n') ) { bNotDone = FALSE; // got telnet eol } if (iIdx == iLen) { return ( -1 ); // error, buffer too small } } szBuf[iIdx - 2] = NULL; // append null termination return ( TRUE ); }