There is a curve class for working with sockets ...

There are 2 questions:

1) When receiving replies, the port remains “forgotten” for some time, how to get rid of it?

2) When receiving the address to which the request came, it will be = 0.0.0.0, how can I get a local and external address?

#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string> use namespace std; class a_socket { public: void init(); void listen_port(); string GetLastAddr(); string GetServerAddr(); string GetLastMessage() { string mess_str(buffer); return mess_str; } private: int sockfd, newsockfd, portno, n; socklen_t clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; }; void error(const char *msg) { perror(msg); exit(1); } void a_socket::init() { sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = 3131; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); } string a_socket::GetLastAddr() { char ip[200]; strcpy(ip, inet_ntoa(cli_addr.sin_addr)); string ipstr(ip); return ipstr; } string a_socket::GetServerAddr() { char ip[200]; strcpy(ip, inet_ntoa(serv_addr.sin_addr)); string ipstr(ip); return ipstr; } void a_socket::listen_port() { listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n", buffer); n = write(newsockfd,"OK", 2); if (n < 0) error("ERROR writing to socket"); close(newsockfd); close(sockfd); } 
  • one
    In order to be able to quickly relocate to the same port / address, such a call is used int option = 1; setsockopt (sockfd, SOL_SOCKET, SO_REUSEPORT | SO_REUSEADDR, (const char *) & option, sizeof option) But usually the code is written so as not to open the server socket for each sneeze. Opened and waiting for connections. - KoVadim
  • Maybe there are already some kind of ready-made solutions for working with sockets? - avengerweb
  • 2
    What problem are you trying to solve? listen/bind/socket/read - these are ready-made solutions for this task. - KoVadim
  • Something like a small server, commands are sent from the web muzzle, the server accepts and processes them. - avengerweb
  • The simplest ready server is inetd / xinetd (or even netcat). Maybe this is exactly what you need? - avp

1 answer 1

I would advise to pay attention to the library for working with the network ASIO