Created
July 27, 2018 06:27
-
-
Save miwarin/b58ee653ae7f93a3ba3f19b343e393e5 to your computer and use it in GitHub Desktop.
TCPサーバー
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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