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
| #include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
#define BUFSIZE 1024
int connexion(char* server_name,int port)
{
int sock;
struct sockaddr_in serverSockAddr;
struct hostent *serverHostEnt;
memset(&serverSockAddr,0,sizeof(serverSockAddr));
serverHostEnt = gethostbyname(server_name); // recupere données sur serveur.
if (serverHostEnt == NULL)
{
printf("Serveur introuvable : %s\n",server_name);
return -1;
}
memcpy(&serverSockAddr.sin_addr,serverHostEnt->h_addr,serverHostEnt->h_length);
serverSockAddr.sin_port = htons(port);
serverSockAddr.sin_family = AF_INET;
sock = socket(AF_INET,SOCK_STREAM,0); // cree la socket
if (sock<0)
{
printf("creation de socket a foire...\n");
return -1;
}
if(connect(sock,(struct sockaddr *)&serverSockAddr,sizeof(serverSockAddr))<0)
{
printf("Impossible de se connecter :(\n");
return -1;
}
return sock;
}
void request(int sock,char* host,char* get)
{
char commande[500];
char buf[BUFSIZE];
int lu;
FILE* F;
sprintf(commande,"GET %s HTTP/1.1\r\nHost: %s\r\nAccept: */*\r\n\r\n",get,host);
send(sock,commande,strlen(commande)+1,0);
F=fopen("IP.html","wb");
do
{
lu=recv(sock,&(buf[0]),BUFSIZE,0);
fwrite(&(buf[0]),lu,1,F);
} while(lu>0);
fclose(F);
}
int main()
{
int sock=-1;
char server_name[]="ip-to-country.com";
char request_host[]="ip-to-country.com";
char request_path[]="/get-country/?ip='1042284544'&user=guest&pass=guest";
int port=80;
WSADATA wsa;
WSAStartup(MAKEWORD(2,0),&wsa);
sock=connexion(server_name,port);
if (sock<0)
return -1;
request(sock,request_host,request_path);
/* fermeture de la connection */
shutdown(sock,2);
closesocket(sock);
WSACleanup( );
return 0;
} |
Partager