00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021 #include "SocketUDP.h"
00022
00023 SocketUDP::SocketUDP(unsigned int port) throw(SocketException) : Socket(port){
00024 struct sockaddr_in adresse;
00025 mSocket=socket(AF_INET,SOCK_DGRAM,0);
00026 if (mSocket<0) throw(SocketException(1));
00027 adresse.sin_family = AF_INET;
00028 adresse.sin_port = htons((u_short)port);
00029 adresse.sin_addr.s_addr = INADDR_ANY;
00030 int retour=bind (mSocket,(struct sockaddr *)&adresse,sizeof(adresse));
00031 if (retour<0) throw(SocketException(2));
00032 mExtremiteDefinie=false;
00033 }
00034
00035 SocketUDP::SocketUDP(string ad, unsigned int port) throw(SocketException): Socket(ad,port){
00036 struct hostent *recup;
00037 mSocket=socket(AF_INET,SOCK_DGRAM,0);
00038 if (mSocket<0) throw(SocketException(1));
00039 if ((recup = gethostbyname(ad.c_str()))==NULL) throw(SocketException(3));
00040 mAdresseDistante.sin_family = AF_INET;
00041 mAdresseDistante.sin_port = htons((u_short)port);
00042 memcpy((char *)&mAdresseDistante.sin_addr, (char *)recup->h_addr, recup->h_length);
00043 mExtremiteDefinie=true;
00044 }
00045
00046 SocketUDP::SocketUDP(const SocketUDP &s){
00047 mSocket=s.mSocket;
00048 mAdresseDistante=s.mAdresseDistante;
00049 mExtremiteDefinie=s.mExtremiteDefinie;
00050 }
00051
00052 void SocketUDP::operator=(const SocketUDP &s){
00053 mSocket=s.mSocket;
00054 mAdresseDistante=s.mAdresseDistante;
00055 mExtremiteDefinie=s.mExtremiteDefinie;
00056 }
00057
00058 SocketUDP::~SocketUDP(){
00059 close(mSocket);
00060 }
00061
00062 void SocketUDP::Envoyer(string msg) const throw(SocketException){
00063 if(mExtremiteDefinie){
00064 int s=sendto(mSocket,mCryptage->Crypter(msg).c_str(),msg.length(),0,(struct sockaddr*)&mAdresseDistante,sizeof(mAdresseDistante));
00065 if (s==-1) throw(SocketException(6));
00066 } else throw(SocketException(8));
00067 }
00068
00069 string SocketUDP::Ecouter() throw(SocketException){
00070 char buffer[BUFSIZ];
00071 socklen_t taille=sizeof(mAdresseDistante);
00072 int s=recvfrom(mSocket,buffer,BUFSIZ,0,(struct sockaddr*)&mAdresseDistante,&taille);
00073 if(s==-1) throw(SocketException(7)); else {
00074 buffer[s]=0;
00075 mExtremiteDefinie=true;
00076 return mCryptage->Decrypter(buffer);
00077 }
00078 }