This is my first socket program. ive created a simple UDP server application which listens to a socket on port 1250 and gives an appropriate reply to based on the input recieved from client on the socket.
Please take a look at my code, comments and critique are appreciated. should i start building my client application now?
BTW. a question about the listen() function.
does the program excution halt on when you call listen() and continue when something is recieved.
or should the server listen(), then loop infinetly and check if something is recieved using accept(). and if accept() returns true then whatever routine should be executed?
#include<iostream>
#include <WinSock2.h>
using namespace std;
void WinConnect(); //open windows connection
int MakeSocket(); //create socket, return descriptor
void ServerSetup(sockaddr_in & , int);
int main()
{
WinConnect();
int sd1 = MakeSocket();
sockaddr_in server; // create server struct
ServerSetup(server,sd1);
listen(sd1,1); //listen to created socket for connection
accept(sd1,0,0); //accept connection on socket
char* buffer = new char[25000];
recv(sd1,buffer,25000,0); //get recieved input and put in buffer
char* reply = new char[25000];
if (strcmp(buffer, "HELLO SERVER") == 0)
{
reply = "HI CLIENT";
send(sd1,reply,strlen(reply),0);
}
else
{
reply = "UNKOWN COMMAND";
send(sd1,reply,strlen(reply),0);
}
return 0;
}
void Winopen()
{
WSADATA w;
if (WSAStartup(0x0101, &w) != 0)
{
cout<< "ERROR: Could Not Open Windows connection."<<endl;
exit(0);
}
}
int MakeSocket()
{
int sd;
sd = socket(AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
{
cout<< "ERROR: Could Not Create Socket."<<endl;
WSACleanup();
exit(0);
}
return sd;
}
void ServerSetup(sockaddr_in & server , int sd)
{
memset(&server, 0, sizeof(server)); //clears out our server struct
server.sin_family = AF_INET; //set server family.. *as socket*
server.sin_port = htons(1250); // set server's port number
//assign server address to 255.255.255.255
//later make function to assign automatically using:
// gethostname(host_name, sizeof(host_name));
// hp = gethostbyname(host_name);
unsigned char a1 = static_cast<unsigned char> (255);
server.sin_addr.S_un.S_un_b.s_b1 = a1;
server.sin_addr.S_un.S_un_b.s_b2 = a1;
server.sin_addr.S_un.S_un_b.s_b3 = a1;
server.sin_addr.S_un.S_un_b.s_b4 = a1;
//bind server adress to the socket created
if(bind(sd, (struct sockaddr *)&server, sizeof(struct sockaddr_in)) ==SOCKET_ERROR)
{
WSACleanup();
closesocket(sd);
exit(0);
}
}