1

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?

1
  • You'll need to pass both the buffer and the length to onReceive(). Commented Mar 4, 2015 at 22:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

A pointer is not necessarily 4 bytes, but yes sizeof(char *) is the size of the pointer not the length of the data contained.
Hm I changed that to be the actual size, and now it's not receiving 0.0.0.0 but it's still the wrong address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.