Code:
#include <winsock.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MESSAGE "operator"
int main()
{
WSADATA wsda;
struct hostent *host;
FILE *outputfile;
char szInBuffer[128];
int iBufferLen;
char szMessage[80];
int iMessageLen=0;
int ret;
char szAddress[]="sco3";
int iPort = 23; /* telnet port*/
SOCKET s;
SOCKADDR_IN addr;
strcpy(szMessage, MESSAGE);
// load version 1.1 of winsock
WSAStartup(MAKEWORD(1,1), &wsda);
if ((outputfile = fopen("C:\\messages.txt", "a+")) == NULL)
{
fprintf(stderr, "Cannot open %s\n", outputfile);
return 0;
}
// create a tcp socket
fprintf(outputfile,"Creating a socket....\n");
s=socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
// error creating socket ?
if (s == SOCKET_ERROR){
fprintf(outputfile,"ERROR --- Call to socket(AF_INET, SOCK_STREAM, IPPROTO_IP); failed with:\n%d\n", WSAGetLastError());
exit(1);
}
fprintf(outputfile,"Everything going OK\n");
// fill in host information
addr.sin_family = AF_INET;
addr.sin_port = htons(iPort);
addr.sin_addr.s_addr = inet_addr(szAddress);
// if the address was not in numeric form, resolve it....
if(addr.sin_addr.s_addr == INADDR_NONE){
host=NULL;
fprintf(outputfile,"Resolving host....\n");
host=gethostbyname(szAddress);
if(host==NULL){
fprintf(outputfile,"Error --- unknown host: %s\n", szAddress);
exit(1);
}
memcpy(&addr.sin_addr, host->h_addr_list[0], host->h_length);
fprintf(outputfile,"OK, moving on .....\n");
}
// connecting to the server
fprintf(outputfile,"Connecting to %s: Port %d\n", szAddress, iPort);
ret = connect(s, (struct sockaddr *) &addr, sizeof(addr));
if(ret == SOCKET_ERROR){
fprintf(outputfile,"ERROR --- Call to connect(s, (SOCKADDR)addr, sizeof(addr)) failed with:\n%d\n", WSAGetLastError());
exit(1);
}
fprintf(outputfile,"Connected !!\n");
// send data
fprintf(outputfile,"Sending data.....\n");
ret = send(s, szMessage, iMessageLen, 0);
if(ret == SOCKET_ERROR){
fprintf(outputfile,"ERROR --- Call to send(s, szMessage, iMessageLen, 0) failed with:\n%d\n", WSAGetLastError());
exit(1);
}
// receive data
fprintf(outputfile,"Waiting for a response.....\n");
ret = recv(s, szInBuffer, sizeof(szInBuffer), 0);
if(ret == SOCKET_ERROR){
fprintf(outputfile,"ERROR --- Call to recv(s, szInBuffer, sizeof(szInBuffer), 0) failed with:\n%d\n", WSAGetLastError());
exit(1);
}
fprintf(outputfile,"Response received !\n");
iBufferLen = ret;
szInBuffer[iBufferLen] = '\0';
fprintf(outputfile,"Response received from %s:\n\"%s\"\n", szAddress, szInBuffer);
// cleanup
fclose(outputfile);
closesocket(s);
WSACleanup();
return 0;
}
and here is my outputfile: