#include #include #include #include #include void main(int argc, char *argv[]) { int s, // our socket rc, // return code c, // client socket len; // length of structure struct sockaddr_in server, client; s = socket(AF_INET, SOCK_STREAM, 0); // create a socket if (s < 0){ cerr << "Error! Cannot create socket." << endl; return; } len = sizeof(struct sockaddr_in); bzero(server, len); // clear the data server.sin_family = AF_INET; server.sin_port = htons(7777); server.sin_addr = INADDR_ANY; rc = bind(s, (struct sockaddr *) &server, len); if (rc < 0) { cerr << "Error! Bind failed." << endl; return; } rc = listen(s, SOMAXCONN); // change to passive socket if (rc < 0) { cerr << "Error! Listen failed." << endl; return; } for( ; ; ) { // forever bzero(&client, len); c = accept(s, (struct sockaddr *)&client, &len); if (c < 0) { cerr << "Error! Accept failed." << endl; return; } // do some work with new socket c to client TalkToClient(c); } } // ---------------------------------------------------------------- void TalkToClient(int iSocket) { int iRc, bNotDone; char szBuf[256], szOk[] = "OK", szErr[] = "ERR"; bNotDone = TRUE; while (bNotDone == TRUE) { iRc = RecvLine(iSocket, szBuf, 256); if (iRc < 0) { cerr << "Error! RecvLine failed." << endl; bNotDone = FALSE; } if (strcmp(szBuf, "HELLO") == 0) { iRc = send(iSocket, szOk, strlen(szOk), 0); if (iRc < 0) { cerr << "Error! Send failed." << endl; bNotDone = FALSE } } else if (strcmp(szBuf, "GOODBYE") == 0) { iRc = send(iSocket, szOk, strlen(szOk), 0); if (iRc < 0) { cerr << "Error! Send failed." << endl; bNotDone = FALSE } bNotDone = FALSE; // close connection on GOODBYE } else { // unknown message send(iSocket, szErr, strlen(szErr), 0); bNotDone = FALSE; } } close(iSocket); } // ---------------------------------------------------------------- // 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 ); }