#ifndef unix
#include <winsock2.h>
#else
#define closesocket close
#define SOCKET int
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PROTOPORT 60000
#define QLEN 5
int main(int argc, char *argv[])
{
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
SOCKET sd, sd2;
int port;
#ifdef WIN32
WSADATA wsaData;
if(WSAStartup(0x0101, &wsaData)!=0)
{
fprintf(stderr, "Windows Socket Init failed: %d\n", GetLastError());
exit(1);
}
#endif
memset((char *)&sad,0,sizeof(sad));
if (argc > 1) {
port = atoi(argv[1]);
} else {
port = PROTOPORT;
}
if (port <= 0)
{
fprintf(stderr,"bad port number %s\n",argv[1]);
exit(1);
}
sad.sin_port = htons((u_short)port);
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
ptrp = getprotobyname("tcp");
if ( ptrp == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol number");
exit(1);
}
sd = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed\n");
exit(1);
}
if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"bind failed\n");
exit(1);
}
if (listen(sd, QLEN) < 0) {
fprintf(stderr,"listen failed\n");
exit(1);
}
while (1)
{
int alen;
char buf[1000];
int n;
int m;
alen = sizeof(cad);
sd2=accept(sd, (struct sockaddr *)&cad, &alen);
if ( sd2 < 0) {
fprintf(stderr, "accept failed\n");
exit(1);
}
while (1)
{
n = recv(sd2, buf, sizeof(buf), 0);
if (n<0)
{
fprintf(stderr,"Error in receiving\n");
break;
}
else if (n==0) {
break;
}
else if(n>0)
{
m = send(sd2,buf,n,0);
if(m<0){
fprintf(stderr,"Error in sending\n");
break;
}
}
}
closesocket(sd2);
}
#ifdef WIN32
WSACleanup();
#endif
return(0);
}