#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#define uchar unsigned char
#define DEFAULT_PORT 80
#define DEFAULT_PROTO SOCK_STREAM // TCP
int fun();
int main(int argc, char **argv) {
fun();
return 0;
}
int fun()
{
static char Buffer[1024*1024]={0};
char server_name[256]= "www.163.com";
int retval, loopflag=0;
int loopcount,maxloop=-1;
int socket_type = DEFAULT_PROTO;
struct sockaddr_in cli_addr;
WSADATA wsaData;
if (WSAStartup(0x202,&wsaData) == SOCKET_ERROR) {
fprintf(stderr,"WSAStartup failed with error %d\n",WSAGetLastError());
WSACleanup();
return -1;
}
SOCKET cli_sock=socket(PF_INET,SOCK_STREAM,0);
if (cli_sock==INVALID_SOCKET){
//MessageBox (0,"create socket Error", 0, MB_OK);
return -1;
}
// connect to server
unsigned short netshort;
if(WSAHtons(cli_sock, DEFAULT_PORT, &netshort))
{
//::MessageBox(0, "port error, can‘t convert address", 0, MB_OK);
return -1;
}
hostent* he = NULL;
if ( (he = gethostbyname("www.163.com")) == NULL)
{
//::MessageBox(0, "gethostbyname error", 0, MB_OK);
return -1;
}
struct sockaddr_in srv_addr;
srv_addr.sin_family = AF_INET;
//srv_addr.sin_addr.s_addr = inet_addr("42.81.5.76");
memcpy(&srv_addr.sin_addr, he->h_addr_list[0], he->h_length);
srv_addr.sin_port= netshort;
if (connect(cli_sock,(LPSOCKADDR)&srv_addr,sizeof(srv_addr))==SOCKET_ERROR){
wchar_t errtxt[64];
wsprintf(errtxt, L"connection failed\nserver: %s, port: %d,error =%d\n", server_name, DEFAULT_PORT , WSAGetLastError());
//printf ( errtxt);
return -1;
}
char sz[]="GET /index.html HTTP/1.1\r\nHost:www.163.com\r\n\r\n";//发送http请求,关键就在这里
retval = send(cli_sock,sz,sizeof(sz)-1,0);
if( SOCKET_ERROR == retval )
return 0;
char buffer[1024]={0};
while( SOCKET_ERROR != retval ){
retval = recv(cli_sock ,buffer,1000,0);//接受数据
printf("%s\n",buffer);
}
closesocket(cli_sock);
WSACleanup();
return 1;
}