I took this stright out of the link above.
also added a bit more output.
Code:
#include <winsock.h> // winsock.h always needs to be included
#include <stdio.h>
#define MY_PORT 10000
#define MY_CONNECTIONS 5
int main(int argc, char** argv) {
WORD version = MAKEWORD(1,1);
WSADATA wsaData;
int nRet;
//
// First, we start up Winsock
//
WSAStartup(version, &wsaData);
//
// Next, create the socket itself
//
SOCKET listeningSocket;
listeningSocket = socket(AF_INET, // Go over TCP/IP
SOCK_STREAM, // Socket type
IPPROTO_TCP); // Protocol
if (listeningSocket == INVALID_SOCKET) {
printf("Error at socket()");
WSACleanup();
return 0;
}
printf("Socket created\n");
//
// Use SOCKADDR_IN to fill in address information
//
SOCKADDR_IN saServer;
saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY; // Since this is a server, any address will do
saServer.sin_port = htons(MY_PORT); // Convert int 8888 to a value for the port field
printf("Port: %i\n", MY_PORT);
//
// Bind the socket to our local server address
//
nRet = bind(listeningSocket, (LPSOCKADDR)&saServer, sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR) {
printf("Error at bind()");
WSACleanup();
return 0;
}
//
// Make the socket listen
//
printf("Setting socket to lissen\n");
nRet = listen(listeningSocket, MY_CONNECTIONS); // 10 is the number of clients that can be queued
if (nRet == SOCKET_ERROR) {
printf("Error at listen()");
WSACleanup();
return 0;
}
//
// Wait for a client
//
SOCKET theClient;
printf("Waiting for connections....\nWARNING: Program has been haulted while it waits for connections\n");
theClient = accept(listeningSocket,
NULL, // Address of a sockaddr structure (see below)
NULL); // Address of a variable containing the size of sockaddr
if (theClient == INVALID_SOCKET) {
printf("Error at accept()");
WSACleanup();
return 0;
}
// Send/receive from the client, and finally:
char myBuf[256];
nRet = recv(listeningSocket, // Connected socket
myBuf, // Receive buffer
sizeof(myBuf), // Size of the buffer
0); // More flags
if (nRet == SOCKET_ERROR) {
printf("Error on recv()\n");
//return 0;
}
strcpy(myBuf, "The middle kid is always screwed up.");
nRet = send(listeningSocket, // Pretend this is connected
myBuf, // Our string buffer
strlen(myBuf), // Length of the data in the buffer
0); // Most often is 0, but see end of tutorial for options
if (nRet == SOCKET_ERROR) {
printf("Error on send()\n");
//return 0;
}
printf("Socket clean up\n");
closesocket(theClient);
closesocket(listeningSocket);
//
// Shutdown Winsock
//
WSACleanup();
printf("Returning from main\nProgram ends here\n");
return 0;
}
Code:
output:
Socket created
Port: 10000
Setting socket to lissen
Waiting for connections....
WARNING: Program has been haulted while it waits for connections
Error on recv()
Error on send()
Socket clean up
Returning from main
Program ends here
Press any key to continue