[C] 소켓으로 웹 연결하기

소켓으로 html 연결하기


소켓으로_html_전송.cpp


소스코드가 꽤 길다.

#include

#include

#include

void main()

{

 SOCKET   skSocket;

 sockaddr_in  saServerAddress;

 int    iPort=80,iStatus; //포트번호

 WSADATA   wsaData;

 WORD   wVersionRequested;

 LPHOSTENT  lpHost;

 char   szHost[128];

 char   szSendBuffer[256];

// char            szDataBuffer[32768];

 char   szRecvBuffer[32768];

 int    iBytesSent;

 int    iBytesReceived;

 int i;

 

 sprintf(szHost,"www.empas.com"); //서버 주소.

 wVersionRequested=MAKEWORD(2,0); //winsock 버전

 skSocket=INVALID_SOCKET;

 iStatus=WSAStartup(wVersionRequested,&wsaData);

 skSocket=socket(AF_INET,SOCK_STREAM, 0);// 스트림소켓생성.

 

 if(skSocket==INVALID_SOCKET){

  cout << "**ERROR** could not create socket" << endl;

  WSACleanup();

  exit(1);

 }

 cout << " <--socket created -->" << endl;

 //소켓주소설정

 saServerAddress.sin_family=AF_INET;

 saServerAddress.sin_addr.S_un.S_addr=inet_addr(szHost); //웹서버주소.

 if(saServerAddress.sin_addr.S_un.S_addr==INADDR_NONE){

  cout << "<--lookin up host ip --> " << endl;

  lpHost=gethostbyname(szHost);

  if(lpHost != NULL){

   saServerAddress.sin_addr.S_un.S_addr=( (LPIN_ADDR)lpHost->h_addr)->s_addr;

  }

  else{

   cout << "**ERROR** Could not locat host" << endl;

   WSACleanup();

   exit(1);

  }

 }

 //서버포트 설정.

 saServerAddress.sin_port=htons(iPort);

 //서버접속

 iStatus = connect (skSocket,(struct sockaddr*)&saServerAddress,sizeof(sockaddr));

 if(iStatus==SOCKET_ERROR){

  cout << "**ERROR** Could not connect to server " << endl;

  //clean up winsock

  WSACleanup();

  exit(1);

 }

 cout << "<-- CONNECTED to Server -->" << endl;



 //http 요청 

 sprintf(szSendBuffer,"GET / HTTP/1.0\n\n");

 iBytesSent=send(skSocket,szSendBuffer,256,0);

 cout<<"<-- SENT " << iBytesSent << " bytes -- >" << endl;

 //html 파일 수신

 unsigned long nSize = 0;

 int nErr;

 while (1)

 {

 // if (ioctlsocket(skSocket,FIONREAD,&nSize))

  {

   iBytesReceived=recv(skSocket,szRecvBuffer + nSize, 1452,0);

   if (iBytesReceived==SOCKET_ERROR)

   {

    nErr = GetLastError();

    while (nErr == WSAEWOULDBLOCK)

    {

     Sleep(50);

     iBytesReceived=recv(skSocket,szRecvBuffer + nSize, 1452,0);

     nErr = GetLastError();

    }

   }

  }

  if (iBytesReceived==0)

   break;

  else

   nSize += iBytesReceived;

 }

 

 cout<<"<-- received " << nSize << " bytes -- >" << endl;

 FILE *of;

 of=fopen("data.txt","w+");

 

 //받은파일 내용 출력/저장.

 for(i=0; i <=nSize ; i++)

 {

  cout << szRecvBuffer[i] ;

  fprintf(of,"%c",szRecvBuffer[i]);

 }

 cout << endl;cout << endl;

 cout<<"<-- received " << nSize << " bytes -- >" << endl;

 //소켓종료

 closesocket(skSocket);

 WSACleanup();

 //파일 닫기

 fclose(of);

}



'Library > winsock' 카테고리의 다른 글

DisplayText() 함수  (0) 2009.07.14
[C] Critical Section  (0) 2009.04.20
TCP_Server, TCP_Client (API 모드)  (0) 2008.03.01
UDP_EventSelectServer,UDP_EventSelectClient  (0) 2008.02.29

댓글

Designed by JB FACTORY