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 89 90 91 92 93 94 95 96 97 98 99 100
|
#include "cserveur.h"
#include <iostream>
#include <stdlib.h>
#include <winsock2.h>
#include <stdio.h>
#include <fstream>
#include <string.h>
using namespace std;
CServeur::CServeur()
{
memset(hostname,0,sizeof hostname);
cout<<"constructeur..."<<endl;
//WSAStartup
erreur=WSAStartup(MAKEWORD(2,2),&initialisation_win32);
if(erreur!=0){
cout<<"Winsock erreur : "<<erreur<<" ; "<<WSAGetLastError()<<endl;
}
else{
printf("WSAStartup OK \n");
}
//ouverture socket
sock=socket(AF_INET,SOCK_STREAM,0);
if(sock==INVALID_SOCKET){
cout<<"erreur socket"<<endl;
}
else{
cout<<"socket OK"<<endl;
}
newsock=socket(AF_INET,SOCK_STREAM,0);
if(newsock==INVALID_SOCKET){
cout<<"erreur socket"<<endl;
}
else{
cout<<"newsocket OK"<<endl;
}
//socket option
tempo=1;
erreur=setsockopt(sock,IPPROTO_TCP,TCP_NODELAY,(char *)&tempo,sizeof(tempo));
if(erreur!=0){
printf("erreur option : %d %d \n",erreur,WSAGetLastError());
}
else {
cout<<"option OK"<<endl;
}
if((gethostname(hostname,sizeof hostname)!=0)){
printf("erreur\n"); //err
exit(1);
}
printf("nom de l'hote = %s \n",hostname);
remoteHost = gethostbyname(hostname);
if(remoteHost==NULL){
fprintf(stderr,"erreur = %d \n",WSAGetLastError());
exit(1);
}
for(adr=(struct in_addr**)remoteHost->h_addr_list;*adr;adr++){
printf("adresse IP = %s \n",inet_ntoa(**adr));
}
}
void CServeur::Csocket(){
/**************************ECOUTE**************************/
//bind
information_sur_la_source.sin_family=AF_INET;
information_sur_la_source.sin_addr.s_addr=INADDR_ANY; //ecoute sur tte ip locales
information_sur_la_source.sin_port=htons(1234); //ecoute sur le port 12345
erreur=bind(sock,(struct sockaddr*)&information_sur_la_source,sizeof(information_sur_la_source));
if(erreur!=0)
printf("port erreur : %d %d \n",erreur,WSAGetLastError());
else
printf("bind OK , %s\n",&information_sur_la_source);
//listen
int listen(SOCKET sock,int backlog);
if (listen(sock,1) == SOCKET_ERROR) {
cout<<"listen error"<<erreur<<" ; "<<WSAGetLastError()<<endl;;
}
else{
cout<<"listen OK"<<endl;
}
//accept
printf("attente de la reception de demande d'ouverrture de session tcp (SYN)\n");
tempo=sizeof(information_sur_la_source);
newsock=accept(sock,(struct sockaddr*)&information_sur_la_source,&tempo);
if(newsock==INVALID_SOCKET){
printf("session TCP erreur : %d \n",WSAGetLastError());
}
else{
printf("accept OK \n");
}
} |