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); }
listen/bind/socket/read
- these are ready-made solutions for this task. - KoVadim