84 lines
1.5 KiB
C
84 lines
1.5 KiB
C
/* derived from http://www.cs.put.poznan.pl/csobaniec/examples/sockets/server-tcp-simple.c */
|
|
|
|
#include <fcntl.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <netinet/in.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <errno.h>
|
|
|
|
static char msg[] =" Hello from server!\n";
|
|
|
|
#define QUIT 0
|
|
#define S2C 1
|
|
|
|
int main(int argc, char* argv[])
|
|
{
|
|
int sockd, sockd2;
|
|
unsigned int addrlen;
|
|
struct sockaddr_in my_name, peer_name;
|
|
int status;
|
|
int cmd, i=0;
|
|
|
|
/* create a socket */
|
|
sockd = socket(AF_INET, SOCK_STREAM, 0);
|
|
if (sockd == -1)
|
|
{
|
|
perror("Socket creation error");
|
|
exit(1);
|
|
}
|
|
|
|
if (argc < 2)
|
|
{
|
|
fprintf(stderr, "Usage: %s port_number\n", argv[0]);
|
|
exit(1);
|
|
}
|
|
|
|
memset(&my_name, 0x00, sizeof(my_name));
|
|
/* server address */
|
|
my_name.sin_family = AF_INET;
|
|
my_name.sin_addr.s_addr = INADDR_ANY;
|
|
my_name.sin_port = htons(atoi(argv[1]));
|
|
|
|
status = bind(sockd, (struct sockaddr*)&my_name, sizeof(my_name));
|
|
if (status == -1)
|
|
{
|
|
perror("Binding error");
|
|
exit(1);
|
|
}
|
|
|
|
status = listen(sockd, 5);
|
|
if (status == -1)
|
|
{
|
|
perror("Listening error");
|
|
exit(1);
|
|
}
|
|
|
|
while(1)
|
|
{
|
|
/* wait for a connection */
|
|
addrlen = sizeof(peer_name);
|
|
sockd2 = accept(sockd, (struct sockaddr*)&peer_name, &addrlen);
|
|
if (sockd2 == -1)
|
|
{
|
|
perror("Wrong connection");
|
|
exit(1);
|
|
}
|
|
|
|
again:
|
|
read(sockd2, &cmd, sizeof(cmd));
|
|
printf("server got %d. command: %d\n", i, cmd);
|
|
i++;
|
|
if (cmd == S2C)
|
|
write(sockd2, msg, strlen(msg)+1);
|
|
if (cmd != QUIT)
|
|
goto again;
|
|
|
|
close(sockd2);
|
|
}
|
|
|
|
return 0;
|
|
}
|