//A simplest web client
//Written by Shen zhiliang for learning Winsock & HTTP
//zhiliang@sina.com
//1998.7.29
#include "winsock.h"
#include "stdio.h"
#define BUFLEN 4096
void SocketError(char * call)
{
fprintf(stderr," WinSock Error# function: %s, error code:%ld\n",call,WSAGetLastError());
}
main(int argc,char ** argv)
{
int iRes,iPort,iTmp;
SOCKET s,rs;
SOCKADDR_IN sin,rsin;
WSADATA wsad;
WORD wVersionReq;
char recvBuf[BUFLEN];
if(argc<4)
{
fprintf(stderr,"Usage: sockserver ip port message\n");
return -1;
}
if(inet_addr(argv[1])==INADDR_NONE)
{
fprintf(stderr,"Error ip gaving\n");
return -1;
}
iPort=0;
iPort=atoi(argv[2]);
sin.sin_addr.s_addr=inet_addr(argv[1]);
sin.sin_family=PF_INET;
sin.sin_port=htons(iPort);
if(iPort<=0)
{
fprintf(stderr,"must specify a number for port\n");
return -1;
}
wVersionReq=MAKEWORD(1,1);
iRes=WSAStartup(wVersionReq,&wsad);
if(iRes!=0)
{
SocketError("WSAStartup()");
return -1;
}
s=socket(PF_INET,SOCK_STREAM,0);
if(s==INVALID_SOCKET)
{
SocketError("socket()");
return -1;
}
iTmp=sizeof(sin);
fprintf(stderr,"WinSock Client Start......\n");
if(connect(s,(LPSOCKADDR)&sin,iTmp)==SOCKET_ERROR)
{
SocketError("connect()");
closesocket(s);
WSACleanup();
return -1;
}
strcpy(recvBuf,argv[3]);
strcat(recvBuf,"\r\n\r\n");
iRes=send(s,recvBuf,strlen(recvBuf),0);
if(iRes==SOCKET_ERROR)
{
SocketError("send()");
closesocket(s);
WSACleanup();
return -1;
}
printf("Sent Data:\n------------------\n%s\n------------------\n",recvBuf);
FILE * fp=fopen("send.dat","a+b");
if(fp==NULL)
return -1;
iRes=recv(s,recvBuf,BUFLEN,0);
while(iRes!=SOCKET_ERROR&&iRes!=0)
{
printf("Received Data:\n------------------\n%s\n------------------\n",recvBuf);
fwrite(recvBuf,sizeof(char),iRes,fp);
iRes=recv(s,recvBuf,BUFLEN,0);
}
fclose(fp);
closesocket(s);
WSACleanup();
return 0;
}