Fix invalid use of inet_ntoa

inet_ntoa returns a pointer to a fixed buffer.
If called multiple times during the evaluating of an expression the
buffer will be overwritten and the addresses will appear duplicated.
This commit is contained in:
Michele Guerini Rocco 2023-06-17 10:48:22 +02:00
parent 940af5a896
commit e17b206b83
Signed by: rnhmjoj
GPG Key ID: BFBAF4C975F76450
3 changed files with 13 additions and 14 deletions

View File

@ -28,16 +28,18 @@
*/ */
#include "TraceroutePacket.h" #include "TraceroutePacket.h"
#include <sys/socket.h>
#include <arpa/inet.h>
TraceroutePacket::TraceroutePacket(char* localSourceAddress, char* localDestinationAddress, TraceroutePacket::TraceroutePacket(struct sockaddr_in *remoteAddress, struct sockaddr_in *localAddress)
u_int16_t localSourcePort, u_int16_t localDestinationPort)
{ {
sourceAddress = localSourceAddress; sourcePort = ntohs(remoteAddress->sin_port);
sourcePort = localSourcePort; destinationPort = ntohs(localAddress->sin_port);
destinationAddress = localDestinationAddress; inet_ntop(AF_INET, &remoteAddress->sin_addr, sourceAddress, sizeof(sourceAddress));
destinationPort = localDestinationPort; inet_ntop(AF_INET, &localAddress->sin_addr, destinationAddress, sizeof(destinationAddress));
} }
char* TraceroutePacket::getSourceAddress(void) { char* TraceroutePacket::getSourceAddress(void) {
return sourceAddress; return sourceAddress;
} }

View File

@ -31,12 +31,13 @@
#define TRACEROUTE_PACKET_H #define TRACEROUTE_PACKET_H
#include <sys/types.h> #include <sys/types.h>
#include <arpa/inet.h>
class TraceroutePacket { class TraceroutePacket {
private: private:
char* sourceAddress; char sourceAddress[INET_ADDRSTRLEN];
char* destinationAddress; char destinationAddress[INET_ADDRSTRLEN];
u_int16_t sourcePort; u_int16_t sourcePort;
u_int16_t destinationPort; u_int16_t destinationPort;
@ -44,8 +45,7 @@ class TraceroutePacket {
/* void setSourceAddress(char* localSourceAddress); */ /* void setSourceAddress(char* localSourceAddress); */
/* void setSourcePort(u_int16_t localSourcePort); */ /* void setSourcePort(u_int16_t localSourcePort); */
/* void setDestinationPort(u_int16_t localDestinationPort); */ /* void setDestinationPort(u_int16_t localDestinationPort); */
TraceroutePacket(char* sourceAddress, char* destinationAddress, TraceroutePacket(struct sockaddr_in *remoteAddress, struct sockaddr_in *localAddress);
u_int16_t sourcePort, u_int16_t destinationPort);
char* getSourceAddress(void); char* getSourceAddress(void);
char* getDestinationAddress(void); char* getDestinationAddress(void);
u_int16_t getSourcePort(void); u_int16_t getSourcePort(void);

View File

@ -76,8 +76,5 @@ class TraceroutePacket* TracerouteReader::readPacket(int fd) {
} }
} }
return new TraceroutePacket(inet_ntoa(remoteAddress.sin_addr), return new TraceroutePacket(&remoteAddress, &localAddress);
inet_ntoa(localAddress.sin_addr),
ntohs(remoteAddress.sin_port),
ntohs(localAddress.sin_port));
} }