Hi! This time I tried to learn winsock. The problem is- I can't receive anything. Here's my code:
Code:
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <stdio.h>
using namespace std;
#pragma comment (lib, "wsock32.lib")
#define NETWORK_ERROR -1
#define NETWORK_OK 0
int host();
int join();
int cinis;
int main()
{
WSADATA wsaData;
WORD version = MAKEWORD( 1, 1 );
int error = WSAStartup( version, &wsaData );
cout<<"1. Host\n2. Join\n";
cin>>cinis;
cin.ignore();
if(cinis==1)
host();
else if(cinis==2)
join();
else
return 0;
cin.get();
}
int host()
{
SOCKET server;
server = socket( AF_INET, SOCK_STREAM, 0 );
struct sockaddr_in sin;
memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(8888);
if ( bind(server, (LPSOCKADDR)&sin, sizeof(struct sockaddr)) == SOCKET_ERROR )
{
cout<<"Error";
std::cin.get();
}
while ( listen( server, SOMAXCONN ) == SOCKET_ERROR )
{
cout<<"Connecting";
system("cls");
}
SOCKET client;
int length;
length = sizeof sin;
client = accept( server, (LPSOCKADDR)&sin, &length );
char * msg= "yay";
send(client, msg, 10, 0);
closesocket( server );
closesocket(client);
WSACleanup();
return 1;
}
int join()
{
SOCKET client;
client = socket( AF_INET, SOCK_STREAM, 0 );
/*struct hostent*/ LPHOSTENT host;
in_addr iaHost;
iaHost.s_addr = inet_addr("127.0.0.1");
host = gethostbyaddr((const char *)&iaHost, sizeof(struct in_addr), AF_INET);
struct sockaddr_in sin;
memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ((struct in_addr *)(host->h_addr))->s_addr;
sin.sin_port = htons( 21 );
if ( connect( client, (LPSOCKADDR)&sin, sizeof sin ) == SOCKET_ERROR )
{
/* could not connect to server */
cout<<"Can't connect";
}
else cout<<"connected!";
char * msg1="";
recv(client, msg1, 10, 0);
cout<<"received: "<<msg1;
closesocket(client);
WSACleanup();
return 1;
}
To test, I just open two instances of my program and try to connect between them, is that correct? Also, the program hangs up when I try to host. I used this and this tutorial. Any assistance or links to better tutorials (or am I the only problem?) appreciated.