* (这就是dos拒绝服务攻击的基础)。
*/
status = listen(serverSocket, BACK_LOG);
if (-1 == status)
{
perror("listen()");
exit(1);
}
/* 从这里开始,套接口就开始准备接受请求,并为他们服务。
* 本例子是用for循环来达到这个目的。一旦连接被接受(accpepted),
* 服务器可以通过指针获得客户的地址以便进行一些诸如记录客户登陆之类的
* 任务。
for (;;)
{
struct sockaddr_in clientName = { 0 };
int slaveSocket, clientLength =
sizeof(clientName);
(void) memset(&clientName, 0,
sizeof(clientName));
slaveSocket = accept(serverSocket,
(struct sockaddr *) &clientName,
&clientLength);
if (-1 == slaveSocket)
{
perror("accept()");
exit(1);
}
childPid = fork();
switch (childPid)
{
case -1: /* ERROR */
perror("fork()");
exit(1);
case 0: /* child process */
close(serverSocket);
if (-1 == getpeername(slaveSocket,
(struct sockaddr *) &clientName,
&clientLength))
{
perror("getpeername()");
}
else
{
printf("Connection request from %s\n",
inet_ntoa(clientName.sin_addr));
}
/*
* Server application specific code
* goes here, e.g. perform some
* action, respond to client etc.
*/
write(slaveSocket, MESSAGE,
strlen(MESSAGE));
/* 也可以使用带缓存的ANSI函数fprint,
* 只要你记得必要时用fflush刷新缓存
*/
close(slaveSocket);
exit(0);
default: /* parent process */
close(slaveSocket);/* 这是一个非常好的习惯
* 父进程关闭子进程的套接口描述符
* 正如上面的子进程关闭父进程的套接口描述符。
*/
}
}
return 0;
}