#include "os_base.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
static int32_t
sock_read_fn(int32_t fd, int32_t revents, void *data)
{
char recv_data[1024];
char send_data[1024];
int bytes_recieved;
if (revents & POLLHUP) {
printf("Socket %d peer closed\n", fd);
close(fd);
}
bytes_recieved = recv(fd, recv_data, 1024, 0);
if (bytes_recieved < 0) {
perror("recv");
}
recv_data[bytes_recieved] = '\0';
if (strcmp(recv_data, "q") == 0 || strcmp(recv_data, "Q") == 0) {
printf("Quiting connection from socket %d\n", fd);
close(fd);
} else {
printf("Recieved: %s\n", recv_data);
snprintf(send_data, 1024, "ACK %d bytes", bytes_recieved);
if (send(fd, send_data, strlen(send_data), 0) < 0) {
close(fd);
}
}
}
static int32_t
sock_accept_fn(int32_t fd, int32_t revents, void *data)
{
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(struct sockaddr_in);
int connected = accept(fd, (struct sockaddr *)&client_addr, &sin_size);
if (connected < 0) {
perror("accept");
}
printf("I got a connection from (%s , %d)\n",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
}
static int32_t
please_exit_fn(int32_t rsignal, void *data)
{
printf("Shutting down at you request...\n");
}
int
main(int argc, char *argv[])
{
int sock;
int true_opt = 1;
struct sockaddr_in server_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("Socket");
exit(1);
}
if (setsockopt(sock,
SOL_SOCKET,
SO_REUSEADDR, &true_opt, sizeof(int)) == -1) {
perror("Setsockopt");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero), 8);
printf("TCPServer binding to port 5000\n");
if (bind(sock,
(struct sockaddr *)&server_addr,
sizeof(struct sockaddr)) == -1) {
perror("Unable to bind");
exit(1);
}
printf("TCPServer Waiting for client on port 5000\n");
if (listen(sock, 5) == -1) {
perror("Listen");
exit(1);
}
close(sock);
return 0;
}