#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 <string.h>
#define PORT 1200
#define QLEN 3
int main()
{
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
SOCKET sd, sd2;
int alen;
#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));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
sad.sin_port = htons((u_short)PORT);
ptrp = getprotobyname("tcp");
if ( ptrp == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol number\n");
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);
}
{
char buf[1000];
char name[80];
int visits = 0;
while (1) {
alen = sizeof(cad);
sd2=accept(sd, (struct sockaddr *)&cad, &alen);
if ( sd2<0) {
fprintf(stderr, "accept failed\n");
exit(1);
}
sprintf(buf,"Welcome to the server.\r\nWhat is your name please?\r\n");
send(sd2,buf,strlen(buf),0);
{
int len=0;
char bch;
while (1) {
if (recv(sd2,&bch,1,0) < 0) break;
else if (bch=='\n') break;
else if (bch=='\r') ;
else
{
name[len]=bch;
len++;
}
if (len+1>=sizeof(name)) break;
}
name[len]='\0';
}
fprintf(stdout, "%s has just contacted us.\n", name);
visits++;
sprintf(buf,"Nice to meet you %s.\r\nYou are the %dth person who stopped by today\r\n", name, visits);
send(sd2,buf,strlen(buf),0);
closesocket(sd2);
}
}
#ifdef WIN32
WSACleanup();
#endif
return(0);
}