My full code looks like this:
#include<stdio.h>
#include<conio.h>
#pragma comment(lib,"mpr.lib")
#pragma comment(lib,"wsock32.lib")
// -lws2_32 compile flag
#include<stdlib.h>
#include<winsock2.h>
int main()
{
//Initialise Winsock API with version details specified in MAKEWORD
WSADATA WsaDat;
if(WSAStartup(MAKEWORD(1,1),&WsaDat)!=0)
printf("\nWSA Initialization failed.");
//Define a socket using the socket() function
SOCKET socketDefinition;
socketDefinition=socket(AF_INET,SOCK_STREAM,0);
if(socketDefinition==INVALID_SOCKET)
printf("\nSocket creation failed!");
//Bind it to a TCP/IP port
SOCKADDR_IN SockAddr;
SockAddr.sin_port=24; /*Port to be used*/
SockAddr.sin_family=AF_INET; /*Connection Type: TCP/IP*/
/*Listen on IP address: 127.0.0.1*/
SockAddr.sin_addr.S_un.S_un_b.s_b1 = 127;
SockAddr.sin_addr.S_un.S_un_b.s_b2 = 0;
SockAddr.sin_addr.S_un.S_un_b.s_b3 = 0;
SockAddr.sin_addr.S_un.S_un_b.s_b1 = 1;
if(bind(socketDefinition,(SOCKADDR*)(&SockAddr),sizeof(SockAddr))==SOCKET_ERROR)
printf("Attempt to bind failed.");
//Listen to a socket
listen(socketDefinition,1);
//Wait/Loop until a connection received
SOCKET TempSock = SOCKET_ERROR;
while(TempSock==SOCKET_ERROR)
TempSock=accept(socketDefinition, NULL, NULL);
socketDefinition=TempSock;
//Get information on who connected
SOCKADDR Addr;
accept(socketDefinition,&Addr,(int*)sizeof(Addr));
//Connect to the incoming request with port and address of the one trying to connect to
if (connect(socketDefinition,(SOCKADDR *)(&SockAddr),sizeof(SockAddr))!=0)
printf("Failed to establish connection with server.");
//The sending function
char* str="Hello";
int RetVal=SOCKET_ERROR;
while (RetVal==SOCKET_ERROR)
{
RetVal = recv(socketDefinition,str,strlen(str)+ 1,0);
if ((RetVal==0)||(RetVal==WSAECONNRESET))
{
printf("Connection closed at the sending moment.");
break;
}
}
//Receive in the same looping manner as above
while (RetVal==SOCKET_ERROR)
{
RetVal=recv(socketDefinition,str,50,0);
if ((RetVal == 0)||(RetVal == WSAECONNRESET))
{
printf("Connection closed at other end.");
break;
}
}
getch();
return 0;
}