Reputation: 217
I am trying to send packets via UDP, and I am not allowed to use SOCK_RAW (school project). The packet I am sending has a header struct ip and a string data part. I put them into one char array (the packet itself is configured correctly).
Here is how I send:
sendPacket(packet);
where packet is a char[] and
where sendPacket is defined as:
void IPNode::sendPacket(char* packet){
//define socket, destSockAddr
int success = sendto(socket, packet, sizeof(packet), 0,
(struct sockaddr *) &destSockAddr, sizeof(destSockAddr));
}
}
The packet seems to be correct. However, this is how I read it in.
while (true) {
struct sockaddr_in remoteAddr;
socklen_t remoteAddrLen = sizeof(remoteAddr);
char buffer[BUF_SIZE];
int recvlen = recvfrom(myListenSocket, buffer, BUF_SIZE, 0, 0, 0);
onReceive(buffer);
// other stuff
}
where onReceive is:
void onReceive(char* packet) {
ip* ptr = (ip*)packet; //the struct ip is the beginning of the packet
struct ip ipCpy = *ptr;
struct in_addr inAddrCpy = ipCpy.ip_src;
char* ipString = inet_ntoa(inAddrCpy);
cout << ipString << endl;
return;
}
However, the ipString that is printed is different from the ipString that was in the packet before being sent. Am I accessing the received packets wrongly?
Upvotes: 1
Views: 790
Reputation: 10415
You are sending sizeof(packet) bytes. But sizeof(packet) is 4, because packet is a pointer. You need a better way to keep track of the actual size you want to send.
Upvotes: 1