1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
|
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#define RECIEVE_BUFFER_SIZE 1024
int main ()
{
int Socket_Listen=0;
int Socket_Accept=0;
int Byte_Recieved=0;
int i=0;
fd_set Master;
int Fd_Max=0;
FD_ZERO(&Master);
int Select_Return_Value=0;
socklen_t addrlen=0;
struct sockaddr_in Address;
char * Message= "You are connected to this server :) . \n";
char * Message_Recieved_OK="Hey I got your message\n";
char * Recieved_Text;
Recieved_Text=(char*)malloc(RECIEVE_BUFFER_SIZE);
memset(Recieved_Text,0,RECIEVE_BUFFER_SIZE);
Address.sin_family = AF_INET;
Address.sin_addr.s_addr = INADDR_ANY;
Address.sin_port = htons(10000);
//Create Socket
Socket_Listen = socket(AF_INET,SOCK_STREAM,0);
if (Socket_Listen < 0)
{
perror("Could niot Create Socket!");
exit(EXIT_FAILURE);
}
else
{
fcntl(Socket_Listen, F_SETFL, O_NONBLOCK);
}
if (bind(Socket_Listen,(struct sockaddr*)&Address,sizeof(Address)) <0)
{
perror("Could not bind!");
exit(EXIT_FAILURE);
}
if (listen(Socket_Listen,3) < 0)
{
perror("Could not Listen on port.");
exit(EXIT_FAILURE);
}
Fd_Max = Socket_Listen;
FD_SET(Socket_Listen, &Master);
addrlen=sizeof(Address);
while (1)
{
Select_Return_Value = select(Fd_Max +1,&Master,NULL,NULL,NULL);
if ( (Select_Return_Value < 0 ) && (errno!=EINTR))
{
perror("Problem in return Select Funstion!");
}
else
{
for (i=0; i <= Fd_Max; i++)
{
if (FD_ISSET(i,&Master))
{
if (i == Socket_Listen)
{
//There is New Connection request
Socket_Accept = accept(Socket_Listen,(struct sockaddr *)&Address,&addrlen);
if (Socket_Accept < 0)
{
perror("Can Not Accept Any Connection");
exit(EXIT_FAILURE);
}
FD_SET(Socket_Accept,&Master);
if ( Socket_Accept > Fd_Max)
Fd_Max =Socket_Accept;
if (send(Socket_Accept,Message,strlen(Message),0) < 0 )
{
perror("Could not send to client!");
exit(EXIT_FAILURE);
}
} else
{
Byte_Recieved=recv(i,Recieved_Text,RECIEVE_BUFFER_SIZE,0);
if (Byte_Recieved < 0)
{
perror("Could not get data from client!");
exit(EXIT_FAILURE);
}else if (Byte_Recieved == 0)
{
printf ("Connection failed!");
exit (EXIT_FAILURE);
}else if (Byte_Recieved > 0)
{
printf("client sent %d byte to server.\n",Byte_Recieved);
if (send(i,Message_Recieved_OK,strlen(Message_Recieved_OK),0) < 0 )
{
perror("Could not send to client the message!");
exit(EXIT_FAILURE);
}
close(i);
FD_CLR(i,&Master);
}
}
}
}
}
}
return 0;
}
|