Denne kode sender en Get kommando til en webserver (google.com) og får en hjemmeside tilbage.
#include <iostream.h> #include <winsock.h>
void main() { char tpkt[21] = "GET / HTTP/1.0 \n\n"; /* message to send to host */ char servername[80]="216.239.37.101"; /* pointer to name of server */ struct hostent *h; /* getnamebyhost info returned */ struct sockaddr_in sa; /* socket address */ int fd; /* socket descriptor */ short portnum=80; /* port number of server */ int funcstatus; /* returned status from socket functions */ int inlen; /* length of input message */ char inbuf[200000]; /* input message buffer */ WSADATA wsaData; /* Winsock parameters */
WSAStartup( 0x0101, &wsaData);
/* get host address */ h = gethostbyname(servername); if (h == NULL) { cout << "gethostbyname error"; exit(0); }
/* allocate an open socket */ fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { cout << "socket creation error"; cin.ignore(); exit(0); } else cout << "socket created\n";
/* connect to the server */ if (connect(fd, (struct sockaddr *)&sa, sizeof sa) < 0) { cout << "connect error"; cin.ignore(); exit(0); } cout << "connected\n";
/* send a packet to the server */ funcstatus = send(fd, tpkt, strlen(tpkt)+1, 0 ); if (funcstatus == -1) { cout << "Error sending data to server\n"; cin.ignore(); exit(0); } cout << "packet sent to server\n";
/* wait for a reply */ inlen = recv(fd, inbuf, 200000, 0); if (inlen < 0) cout << "Error receiving data from the server\n"; else cout << inlen << " byte reply from server" << inbuf;
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.