Files
42_INT_12_webserv/srcs/main.cpp
2022-07-13 14:22:26 +02:00

74 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# include <iostream>
# include <cerrno> // errno
# include <cstdio> // perror
# include <sys/socket.h> // socket, accept, listen, send, recv, bind, connect, setsockopt, getsockname
# include <netinet/in.h> // sockaddr_in
# define INVALID_SCKT -1
# define INVALID_BIND -1
# define INVALID_LSTN -1
# define INVALID_AXPT -1
# define PORT 80
# define NB_CONX 20
int main()
{
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int socket_fd;
int new_fd;
int lstn;
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd == INVALID_SCKT)
{
perror("err socket(): ");
return 0;
}
memset(&my_addr, 0, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
// my_addr.sin_addr.s_addr = inet_addr("10.12.110.57");
bind(socket_fd, (struct sockaddr *)&my_addr, sizeof(my_addr));
if (socket_fd == INVALID_BIND)
{
perror("err bind(): ");
return 0;
}
/*
https://beej.us/guide/bgnet/html/index-wide.html#cb29 :
Sometimes, you might notice, you try to rerun a server and bind() fails, claiming “Address already in use.” What does that mean? Well, a little bit of a socket that was connected is still hanging around in the kernel, and its hogging the port. You can either wait for it to clear (a minute or so), or add code to your program allowing it to reuse the port, like this:
int yes=1;
// lose the pesky "Address already in use" error message
if (setsockopt(listener,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes) == -1) {
perror("setsockopt");
exit(1);
}
*/
lstn = listen(socket_fd, NB_CONX);
if (lstn == INVALID_LSTN)
{
perror("err listen(): ");
return 0;
}
new_fd = accept(socket_fd, &their_addr, sizeof(their_addr));
if (new_fd == INVALID_AXPT)
{
perror("err accept(): ");
return 0;
}
return 0;
}