both client & server? [Archive] - C Board

PDA

View Full Version : both client & server?


pode
09-15-2003, 02:46 PM
is it possible to make a connection doing something like i've done
in my code.
a copy of the program is ment to be used on another computer
ive tried executing 2 copies and tested it on my own machine.
the problem is that it detects the other user but u cant send and receive anything.
i dont know if its a miss ive done in the code or its something with my computer or localserver.
can someone with a good knowledge in networking explain to me what is wrong



#include <string.h>
#include <iostream.h>
#pragma comment (lib,"wsock32.lib")
#include <winsock.h>
#define PORT 7777
int main()
{


char *buf="MESSAGE";
char *rec=new char[256];
WORD sockVersion;
WSADATA wsaData;
sockVersion = MAKEWORD(2,0);
WSAStartup(sockVersion, &wsaData);



SOCKET sock1, sock2;

sock1=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);


HOSTENT *host;
host=gethostbyname("localhost");

SOCKADDR_IN in_s, ut_s;

in_s.sin_family=AF_INET;
in_s.sin_addr.s_addr=0;
in_s.sin_port=htons(PORT);

ut_s.sin_family=AF_INET;
ut_s.sin_port=htons(PORT);
ut_s.sin_addr=*((LPIN_ADDR)*host->h_addr_list);



int b=bind(sock1,(const struct sockaddr*)&in_s,sizeof(struct sockaddr));
if(b==INVALID_SOCKET)
{
cout<<"error bind()";
}


int l=listen(sock1,10);
if(l==SOCKET_ERROR)
{
cout<<"error listen()";
}


int size=sizeof(struct sockaddr_in);

sock2=accept(sock1,(struct sockaddr*)&ut_s,&size);
if(sock2==SOCKET_ERROR)
{
cout<<"error accept()";
}


int s=send(sock2,buf,strlen(buf),0);
if(s==SOCKET_ERROR)
{
cout<<"error send()";
}
int r=recv(sock2,rec,sizeof(rec),0);
if(r==SOCKET_ERROR)
{
cout<<"error recv()";
}

int c=connect(sock1,(struct sockaddr*)&ut_s,sizeof(struct sockaddr));
if(c==SOCKET_ERROR)
{
cout<<"error connect()";
}










closesocket(sock1);
closesocket(sock2);
WSACleanup();
return 0;
}

thanks for your help!

Hammer
09-15-2003, 04:36 PM
Here's one clue, run this and understand the results it gives.

#include <iostream>
using namespace std;
int main(void)
{
char *rec = new char[256];
cout <<sizeof(rec) <<endl ;
return(0);
}


Also, when you encounter an error, for example bind() fails, you might want to exit the program as opposed to just carry on regardless. ;)

You don't issue connect()'s on sockets that you're using to listen on either.

pode
09-16-2003, 07:59 AM
so what am i doing wrong to get a connection?

Hammer
09-16-2003, 02:13 PM
Create two different programs, one a client, the other a server. That way it'll be easier to understand how they interact. You can still run both on the same machine, and connect to yourself.