Skip to content

Instantly share code, notes, and snippets.

@miwarin
Created July 27, 2018 06:27
Show Gist options
  • Save miwarin/b58ee653ae7f93a3ba3f19b343e393e5 to your computer and use it in GitHub Desktop.
Save miwarin/b58ee653ae7f93a3ba3f19b343e393e5 to your computer and use it in GitHub Desktop.
TCPサーバー
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 465
int main(int ac, char** av)
{
int soc;
struct sockaddr_in sa = {0};
if((soc = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
return EXIT_FAILURE;
}
sa.sin_family = AF_INET;
sa.sin_port = htons(PORT);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(soc, (struct sockaddr*)&sa, sizeof(sa)) == -1)
{
perror("bind");
close(soc);
return EXIT_FAILURE;
}
if(listen(soc, 32) == -1)
{
perror("listen");
close(soc);
return EXIT_FAILURE;
}
for(;;)
{
char recv_buf[1024];
int recv_size;
int fd;
if((fd = accept(soc, NULL, NULL)) == -1)
{
perror("accept");
close(soc);
return EXIT_FAILURE;
}
if((recv_size = read(fd, recv_buf, sizeof(recv_buf) - 1)) == -1)
{
perror("read");
close(soc);
return EXIT_FAILURE;
}
recv_buf[recv_size] = '\0';
puts(recv_buf);
close(fd);
}
close(soc);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment