wip first connexion

This commit is contained in:
hugogogo
2022-07-13 14:22:26 +02:00
parent 340785ef0f
commit 75d6c941a6
3 changed files with 66 additions and 4 deletions

View File

@@ -1,15 +1,73 @@
# 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()
{
int server_fd;
if (server_fd = socket(domain, type, protocol)
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("cannot create socket");
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;
}