PracticeDev/study_clang/socket/demo_tcp6_server.c

79 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BACKLOG 16
int listen_fd = -1;
void sigINT(int signo);
int main()
{
if (signal(SIGINT, sigINT) == SIG_ERR)
{
printf("set signal handler(SIGINT) error!!!\n");
exit(1);
}
// socket
if ( (listen_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0 )
{
printf("create socket error=%d(%s)!!!\n", errno, strerror(errno));
exit(1);
}
// bind
struct sockaddr_in6 server_addr;
server_addr.sin6_family = AF_INET6; // IPv4
server_addr.sin6_port = htons(12500); // Port
server_addr.sin6_addr = in6addr_any; // IP
if (bind(listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
printf("socket bind error=%d(%s)!!!\n", errno, strerror(errno));
exit(1);
}
// listen
if (listen(listen_fd, BACKLOG) < 0)
{
printf("socket listen error=%d(%s)!!!\n", errno, strerror(errno));
exit(1);
}
printf("server init ok, start to accept new connect...\n");
while (1)
{
// accept
int client_fd = accept(listen_fd, NULL, NULL);
if (client_fd < 0)
{
printf("socket accept error=%d(%s)!!!\n", errno, strerror(errno));
exit(1);
}
printf("accept one new connect(%d)!!!\n", client_fd);
static const char *msg = "Hello, Client!\n";
if (write(client_fd, msg, strlen(msg)) != strlen(msg))
{
printf("send msg to client error!!!\n");
}
close(client_fd);
}
}
void sigINT(int signo)
{
printf("catch SIGINT, quit...\n");
close(listen_fd);
exit(0);
}