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
|
#define port 23
#include <iostream>
#include <windows.h>
#include <ws2tcpip.h>
#include <string>
using namespace std;
int main()
{
WSADATA WSAData;
SOCKET sock;
SOCKET csock;
SOCKADDR_IN sin;
SOCKADDR_IN csin;
WSAStartup(MAKEWORD(2, 0), &WSAData);
sock = socket(AF_INET, SOCK_STREAM, 0); // kbw: You should specify the second parameter, it's IPPROTO_TCP
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
bind(sock, (SOCKADDR *)&sin, sizeof(sin));
listen(sock, 0); // kbw: zero buffer size? Winsock allows upto 5 as I recall
while (1) /* Boucle infinie. Exercice : améliorez ce code. */
{
int sinsize = sizeof(csin);
if ((csock = accept(sock, (SOCKADDR *)&csin, &sinsize)) != INVALID_SOCKET)
{
bind(csock, (sockaddr*)&csin, sizeof(csin)); // kbw: why are we binding the client socket? It's already need assiged that address
send(csock, "Hello World, how are you ? \r\n", 32, 0); // kbw: 32 is larger than the string length
char * c_ip = inet_ntoa(csin.sin_addr);
int cport = csin.sin_port;
cout << "Client IP is: " << c_ip << ":" << cport <<endl;
char *buffer = new char[256]; // kbw: this is never free'd
//memset(buffer,0,sizeof(buffer));
int size_buff;
int n;
size_buff = sizeof(buffer); // kbw: sizeof(buffer) is 4, not 256, the rest will be broken as a result
do
{
n += recv(csock, buffer, size_buff, 0);
}
while(*buffer == "\n")
if(n<0)
{
cout << "Error receiving..." << endl;
}
cout << "le message recu est: " << buffer;
closesocket(csock);
}
}
return 0;
}
|