-
winsock help needed
Does anyone know of a good winsock tutorial?
This code is pretty much straight from the MS website and I'm using MSVC++ 6 SP5. It compiles fine, but when I try to link it, I get link errors for every function that should be in winsock2.h
Code:
#include <stdio.h>
#include "winsock2.h"
int main() {
// Initialize Winsock.
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ( iResult != NO_ERROR )
printf("Error at WSAStartup()\n");
// Create a socket.
SOCKET m_socket;
m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if ( m_socket == INVALID_SOCKET ) {
printf( "Error at socket(): %ld\n", WSAGetLastError() );
WSACleanup();
return(0);
}
// Connect to a server.
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );
clientService.sin_port = htons( 27015 );
if ( connect( m_socket, (SOCKADDR*) &clientService, sizeof(clientService) ) == SOCKET_ERROR) {
printf( "Failed to connect.\n" );
WSACleanup();
return(0);
}
// Send and receive data.
int bytesSent;
int bytesRecv = SOCKET_ERROR;
char sendbuf[32] = "Client: Sending data.";
char recvbuf[32] = "";
bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 );
printf( "Bytes Sent: %ld\n", bytesSent );
while( bytesRecv == SOCKET_ERROR ) {
bytesRecv = recv( m_socket, recvbuf, 32, 0 );
if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) {
printf( "Connection Closed.\n");
break;
}
if (bytesRecv < 0)
return(0);
printf( "Bytes Recv: %ld\n", bytesRecv );
}
return(0);
}
-
link with ws2_32.lib
Also, do the winsock include as #include <winsock2.h>
Also, your recv loop is broken - recv returns the number of bytes received. Looping while your variable is equal to SOCKET_ERROR is the opposite of what you want.
If the return code of recv *is* SOCKET_ERROR, check the winsock error with WSAGetLastError(). If recv returns zero, the connection has been (gracefully) closed. Otherwise the return value is the number of bytes written to your buffer.
Winsock info: http://tangentsoft.net/wskfaq/
-
Like I said, the code is straight from MS. They didn't even have int main! They use void main()!!!
I linked with that library and it worked. Thank you :)
-
Sorry forgot it was straight from MS :) There *are* some good winsock articles on the MSDN site though, for server design.
-
Well... I'm just trying to learn sockets in general for now. I'm going to be interacting with a network at work and I'm trying to learn what I can. I'm going to be working with a networking driver soon and I need to read up on this stuff.
-
Check out the links on my website:
http://techno-coding.com/pages/links.htm
Near the bottom. That should help you get started.