Skip to content

Instantly share code, notes, and snippets.

@miwarin
Created July 27, 2018 08:12
Show Gist options
  • Save miwarin/b74cd28cc310eb3eb020d8a9af1ae425 to your computer and use it in GitHub Desktop.
Save miwarin/b74cd28cc310eb3eb020d8a9af1ae425 to your computer and use it in GitHub Desktop.
TCPサーバー poll で複数ポートを待ち受ける
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <poll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT1 25
#define PORT2 465
#define CONN_MAX 2
int main(int ac, char** av)
{
int i;
int optval;
int port[CONN_MAX];
int soc[CONN_MAX];
struct sockaddr_in sa[CONN_MAX];
struct pollfd pollfds[CONN_MAX];
port[0] = PORT1;
port[1] = PORT2;
for(i = 0; i < CONN_MAX; i++)
{
if((soc[i] = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
goto FAILURE;
}
sa[i].sin_family = AF_INET;
sa[i].sin_port = htons(port[i]);
sa[i].sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(soc[i], (struct sockaddr*)&sa[i], sizeof(struct sockaddr)) == -1)
{
perror("bind");
goto FAILURE;
}
if(setsockopt(soc[i], SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int)) == -1)
{
perror("setsockopt");
goto FAILURE;
}
if(listen(soc[i], 32) == -1)
{
perror("listen");
goto FAILURE;
}
pollfds[i].fd = soc[i];
pollfds[i].events = POLLIN;
}
for(;;)
{
int rc;
rc = poll(pollfds, CONN_MAX, -1);
if(rc == -1)
{
perror("poll");
goto FAILURE;
}
for(i = 0; i < CONN_MAX; i++)
{
if(pollfds[i].revents & POLLIN)
{
char recv_buf[1024];
int recv_size;
int fd;
if((fd = accept(soc[i], NULL, NULL)) == -1)
{
perror("accept");
goto FAILURE;
}
if((recv_size = read(fd, recv_buf, sizeof(recv_buf) - 1)) == -1)
{
perror("read");
goto FAILURE;
}
recv_buf[recv_size] = '\0';
puts(recv_buf);
close(fd);
}
}
}
FAILURE:
for(i = 0; i < CONN_MAX; i++)
{
close(soc[i]);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment