Prøv denne:
#include <time.h>
#include <errno.h>
#include <windows.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#define TIMEOUT 5 // Max waiting time in sec
std::string SendReceive(char *hostname, int port, const std::string &cmd)
{
int sd, status, len, ix, tmp;
struct sockaddr local,remote;
struct hostent *hostinfo;
fd_set ReadSet;
struct timeval Time;
// create
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd == SOCKET_ERROR)
{
std::cerr << "Error creating socket: " << WSAGetLastError() << std::endl;
return "";
}
// bind
local.sa_family = AF_INET;
memset(local.sa_data, 0, sizeof(local.sa_data));
status = bind(sd, &local, sizeof(local));
if(status == SOCKET_ERROR)
{
std::cerr << "Error binding socket: " << WSAGetLastError() << std::endl;
closesocket(sd);
return "";
}
// lookup host
hostinfo = gethostbyname(hostname);
if(!hostinfo)
{
std::cerr << "Error looking up host: " << hostname << ", " << WSAGetLastError() << std::endl;
closesocket(sd);
return "";
}
// connect to host
remote.sa_family = hostinfo->h_addrtype;
memcpy(remote.sa_data + 2, hostinfo->h_addr_list[0], hostinfo->h_length);
*((short *)remote.sa_data) = port;
tmp = remote.sa_data[0];
remote.sa_data[0] = remote.sa_data[1];
remote.sa_data[1] = tmp;
status = connect(sd, &remote, sizeof(remote));
if(status)
{
std::cerr << "Error connecting to host: " << WSAGetLastError() << std::endl;
closesocket(sd);
return "";
}
// send request
status = send(sd, cmd.c_str(), cmd.size(), 0);
if(status == SOCKET_ERROR)
{
std::cerr << "Error sending request: " << WSAGetLastError() << std::endl;
closesocket(sd);
return "";
}
// read response */
char resp[128]; // Read at most 128 bytes
ix = 0;
memset(&ReadSet, 0, sizeof(ReadSet));
FD_SET(sd, &ReadSet);
Time.tv_sec = TIMEOUT;
Time.tv_usec = 0;
len = 1;
while(len > 0 && select(sd + 1, &ReadSet, 0, 0, &Time) > 0)
{
len = recv(sd, resp + ix, sizeof(resp) - ix - 1, 0);
ix += len;
Time.tv_sec = TIMEOUT;
Time.tv_usec = 0;
}
resp[ix] = 0;
closesocket(sd);
return resp;
}
int main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(1, 1), &wsaData);
std::string Responce = SendReceive("messenger.hotmail.com", 1863, "VER 1 MSNP10 CVR0\\r\\n");
std::cout << "Received: " << Responce << std::endl;
}
Det meste er noget jeg har stjålet.
Virker med MinGW (og derfor nok også med Dev-Cpp), VisualC++ og BorlandC++.