1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
int main(){
long answer;
WSAData wsa;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
//start the DLL of WinSock
answer = WSAStartup(DLLVersion,&wsa);
SOCKADDR_IN addr;
int len = sizeof(addr);
SOCKET client;
int sfd;
sfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(5500);
//now we created a socket with its structure...lets try to connect to google
char websitename[50];
DWORD dwerror;
SOCKADDR_IN server;
server.sin_family = AF_INET;
server.sin_port = htons(80);
websitename = "www.google.com";
cout<<"\nlooking for : "<<websitename<<"....";
hostent *h = gethostbyname(websitename);
if( h == NULL){
dwerror = WSAGetLastError();
if(dwerror == WSAHOST_NOT_FOUND){
cout<<"\nhost not found!";
_getch();
exit(1);
}else if(dwerror = WSANO_DATA){
cout<<"\nno data record is found!";
_getch();
exit(1);
}else {
cout<< "\nresolving name : "<<websitename<<" failed!";
_getch();
exit(1);
}
}
struct in_addr add;
add.s_addr = *(u_long *)h->h_addr_list[0];
cout<<"resolving finished...\nthe ip : ";
cout<<inet_ntoa(add)<<"\n";
memcpy(&server.sin_addr, h->h_addr_list[0], h->h_length);
int c = connect(sfd,(struct sockaddr*)&server,sizeof(server));
if(c == 0){
cout<<"connected successfully....";
}else{
cout<<"error : connection failed!";
}
char *request;
request = "GET / HTTP/1.1\n\rHost: www.google.com\n\rConnection: close\n\r\n\r";
cout<<"\ndata to be sent : "<<request;
int s = send(sfd,request,strlen(request),0);
if(s == -1){
cout<<"\nsending failed!";
getch();
exit(1);
}else{
cout<<"data sent successfully and the length : "<<s<<endl;
}
char *buffer = NULL;
int r;
while(r=recv(sfd,buffer,1024,0)){
cout<<buffer;
}
cout <<"\nevery thing went well.....";
getch();
}
|