dev/c/masync_server/echo-server.c

66 lines
1.4 KiB
C

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
static const char * int2ip(unsigned int ip) {
static char s[16];
sprintf(s,"%d.%d.%d.%d",ip>>24,ip<<8>>24,ip<<16>>24,ip<<24>>24);
return s;
}
int main()
{
int sock, listener;
struct sockaddr_in addr;
char buf[1024];
int bytes_read;
listener = socket(AF_INET, SOCK_STREAM, 0);
if(listener < 0)
{
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(3425);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(2);
}
listen(listener, 1);
//~ printf("%X\n",addr.sin_addr.s_addr);
while(1)
{
socklen_t n = sizeof(struct sockaddr);
sock = accept(listener, (struct sockaddr *)&addr, &n);
printf("incoming request from %s\n",int2ip(ntohl(addr.sin_addr.s_addr)));
//~ printf("%X\n",addr.sin_addr.s_addr);
if(sock < 0)
{
perror("accept");
exit(3);
}
while(1)
{
bytes_read = recv(sock, buf, 1024, 0);
if(bytes_read <= 0) break;
send(sock, buf, bytes_read, 0);
printf("%s", buf);
}
close(sock);
}
return 0;
}