-
winsock problem
why doesn't this work:
PHP Code:
//skeleton server
#include <winsock.h>
#include <iostream.h>
#define PORTNUM 50000 //port number to be used
void DoSomething (SOCKET); //use this to do anything with socket
SOCKET Establish (unsigned short PortNum)
{
char *own_name ;
SOCKET ret_socket; //socket to be returned
sockaddr_in sa; //internet socket address
hostent *hp; //host info
memset (&sa, 0, sizeof (sockaddr_in)); //clear the address (mem space)
gethostname (own_name, sizeof (own_name)); //get local host name - our own
hp = gethostbyname (own_name); //retrieve address info
if (hp == NULL) //hopefully we do exist, and we wont get that error
return INVALID_SOCKET;
sa.sin_family = hp->h_addrtype; //our host address
sa.sin_port = htons (PortNum); //our port number
ret_socket = socket (AF_INET, SOCK_STREAM, 0); //create the socket
if (ret_socket == INVALID_SOCKET) //failed to create socket
return INVALID_SOCKET;
//now, we bind the socket to the internet address
if (bind (ret_socket, (sockaddr *) &sa, sizeof (sockaddr_in)) == SOCKET_ERROR) {
closesocket (ret_socket); //failed to do so, so get rid of the socket
return INVALID_SOCKET;
}
listen (ret_socket, 3); //make the socket listen
return ret_socket;
} //Establish
int main (int argc, char *argv[])
{
SOCKET my_socket; //main socket
if ((my_socket = Establish (PORTNUM)) == INVALID_SOCKET) { //plug in the phone
cout << "Establish: Failed to install socket" << endl;
return 0;
}
for ( ; ; ) { //loop for phone calls
SOCKET new_socket = accept (my_socket, NULL, NULL);
if (my_socket == INVALID_SOCKET) {
cout << "Error waiting for connection" << endl;
return 0;
}
DoSomething (new_socket);
closesocket (new_socket);
}
return 0;
}
void DoSomething (SOCKET sock)
{
//do thing with socket
}
-
i just found out i forgot to initialize Winsock with WSAStartup (..), so i dont get the Init. failed error..but after a bit of running, the program crashes..
-
i changed the
to
PHP Code:
char own_name[256];
that's the way it was in the tutorial (w/ the 256)
why does that work and not the one before??
-
Did you forget the pointer 1x1 ?
char* ptr;
is a wild pointer, it points to a random location (most likely 0xCCCCCCCC), so you can't use it.
char buf[512];
on the other hand is an array of 512 chars, it already has memory allocated.
-
ohh ok..that explains why i would get similar errors in other programs..thanks
why do you call it pointer 1x1?
-
I don't know if that exists in English. The 1x1 ("Ein mal Eins" = "One times One") means "the absolute basics", because it's the first thing you learn in school when multiplying. To know that a pointer declared like char* p; points at random memory is part of the absolute basics of pointers.
-
ooops.. ok..i wont forget again