Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

problems with sockets????

Status
Not open for further replies.

shetlandbob

Programmer
Mar 9, 2004
528
GB
Hello, I know nothing about sockets and how they connect, so this might be a bit basic!!

I'm trying to connect to a socket, so I create a socket as shown below:

Code:
  WSADATA wsData;
  WORD    wVer = MAKEWORD(2,2);
  SOCKET s;
  WSAStartup(wVer,&wsData);
  s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  err = WSAGetLastError();
  if (s == INVALID_SOCKET) MessageBox ("INVALID_SOCKET");

I assume I now have to connect to the socket?? yes? No? Is this when I would have to specify the IP address (etc... what other info do I have to give it?) of the server I'm connecting to that I want to get the information from? (if I'm way off track then feel free to laugh out loud, but at least tell me!!) If thats what I'm to do, how do I do it???

Then do I get a message through the socket by using the following code:

Code:
  char socketMessage[80];
  value = recv ( s, socketMessage, 80, MSG_PEEK );

  err = WSAGetLastError();

  if ( err == WSAENOTCONN ) MessageBox ("WSAENOTCONN" );

If I run the above code then I get the message box about the socket not being connected.

Any help much appreciated, as I'm on a slipery slope with this one!!!
 
to connect to an open server socket from the client side you should do like this:

Code:
	WORD wVersionRequested = MAKEWORD( 2, 2 );
	WSADATA wsd;
	WSAStartup(wVersionRequested, &wsd);

	int s;//SOCKET

	sockaddr_in svr_addr;
	hostent *hp;
	char buf[80] = "hello world";
	if((hp = gethostbyname("HostOfFilipski")) == 0)
	{
		printf("error on calling gethostbyname()\n");
		exit(1);
	}
	strncpy((char*)&svr_addr.sin_addr.S_un.S_un_b, hp->h_addr_list[0], hp->h_length);


	svr_addr.sin_family = hp->h_addrtype;
    //put instead of portnum the nuber of port opened by 
    //server
	svr_addr.sin_port = htons((u_short)PORTNUM);
	if((s = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		printf("error on creating socket\n");
		exit(1);
	}
	if(connect(s, (const sockaddr*)&svr_addr, sizeof(svr_addr)) == -1)
	{
		printf("error on calling connect()\n");
		exit(1);
	}

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top