#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <error.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#define PORT 8888
#define BACKLOG 8
static int alive = 1;
static void sigpipe(int signo)
{
alive = 0;
}
int main(int argc, char *argv[])
{
int fd, sc;
struct sockaddr_in local_addr, client_addr;
int err = -1;
socklen_t optlen = -1;
int optval = -1;
signal(SIGPIPE, sigpipe);
signal(SIGINT, sigpipe);
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd == -1)
{
printf("Socket Error: %s\n", strerror(errno));
return -1;
}
bzero(&local_addr, sizeof(local_addr));
local_addr.sin_family = AF_INET;
local_addr.sin_port = htons(PORT);
local_addr.sin_addr.s_addr = INADDR_ANY;
err = bind(fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr));
if(err == -1)
{
printf("Bind Error: %s\n", strerror(errno));
return -1;
}
optval = 128 * 1024;
optlen = sizeof(optval);
err = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &optval, optlen);
if(err == -1)
{
printf("Setsockopt SO_RCVBUF Error: %s\n", strerror(errno));
}
err = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &optval, optlen);
if(err == -1)
{
printf("Setsockopt SO_SNDBUF Error: %s\n", strerror(errno));
}
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec= 200000;
optlen = sizeof(tv);
err = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, optlen);
if(err == -1)
{
printf("Setsockopt SO_RCVTIMEO Error: %s\n", strerror(errno));
}
err = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, optlen);
if(err == -1)
{
printf("Setsockopt SO_SNDTIMEO Error: %s\n", strerror(errno));
}
err = listen(fd, BACKLOG);
if(err == -1)
{
printf("Listen Error: %s\n", strerror(errno));
}
fd_set fd_read;
tv.tv_usec = 200000;
tv.tv_sec = 0;
while(alive)
{
socklen_t sin_size = sizeof(struct sockaddr_in);
FD_ZERO(&fd_read);
FD_SET(fd, &fd_read);
switch(select(fd+1, &fd_read, NULL, NULL, &tv))
{
case -1:
case 0:
{
continue;
}
default:
{
break;
}
}
sc = accept(fd, (struct sockaddr*)&client_addr,&sin_size);
if(sc == -1)
{
printf("Accept Error: %s\n", strerror(errno));
continue;
}
optval = 10;
optlen = sizeof(optval);
err = setsockopt(sc, IPPROTO_TCP, SO_KEEPALIVE, (char*)&optval, optlen);
if(err == -1)
{
printf("Setsockopt SO_KEEPALIVE Error: %s\n", strerror(errno));
}
optval = 1;
optlen = sizeof(optval);
err = setsockopt(sc, IPPROTO_TCP, TCP_NODELAY, (char*)&optval, optlen);
if(err == -1)
{
printf("Setsockopt TCP_NODELAY Error: %s\n", strerror(errno));
}
struct linger linger;
linger.l_onoff = 1;
linger.l_linger = 0;
err = setsockopt(sc, SOL_SOCKET, SO_LINGER, (char*)&linger, optlen);
if(err == -1)
{
printf("Setsockopt SO_LINGER Error: %s\n", strerror(errno));
}
err = send(sc, "succeed\n", 10, 0);
if(err == -1)
{
printf("Send Error: %s\n", strerror(errno));
}
close(sc);
}
close(fd);
return 0;
}