Reputation: 6371
I am trying to build a packet that will be sent via UDP. However I am not getting the correct data on the receiving side.
In the packet I want to include an IP Header, UDP Header, and the data that needs to be sent. In this case I just want to send the word "Hello" along with random header information.
char *data = "Hello";
char *packet = (char *)malloc(sizeof(struct iphdr) + sizeof(struct udphdr) + strlen(data));
struct iphdr *ip = (struct iphdr*) packet;
struct udphdr *udp = (struct udphdr*) (packet + sizeof(struct iphdr));
char *send_buff = (char *) (packet + sizeof(struct iphdr) + sizeof(struct udphdr));
ip->saddr = inet_addr("1.2.3.4");
ip->daddr = inet_addr("5.6.7.8");
ip->ttl = 5;
udp->source = 5950;
udp->dest = 5950;
udp->len = sizeof(struct udphdr);
udp->check = 0;
strcpy(send_buff, data);
sendto(sock, packet, (sizeof(struct iphdr) + sizeof(struct udphdr) + strlen(data)), ROUTER_IP);
The problem I'm having is that the receiving end just gets random data so I'm assuming the number of bytes is incorrect somewhere.
On the receiving side I have it print out one of the fields of the IP header as a test, but it's not correct.
char recv_buff[1000];
int recv_bytes = recvfrom(sock, recv_buff, sizeof(recv_buff));
struct iphdr *ip = (struct iphdr*) recv_buff;
cout << static_cast<int16_t>(ip->ttl) << endl;
Am I putting the packet together wrong or is there a problem on the receiving end? I used this example http://www.winlab.rutgers.edu/~zhibinwu/html/c_prog.htm as a reference for putting together the packet.
Upvotes: 4
Views: 9697
Reputation: 66
if you are using your own ip and udp headers ON TOP of the stack's I hope you are parsing the data after removing both headers of yours and stack's. If the receiving socket is RAW, you will get the ip and udp headers of the stack as well.
Upvotes: 0
Reputation: 1823
You are creating the socket as socket(AF_INET, SOCK_DGRAM, 0);
meaning that it's a datagram (=UDP, typically) socket, so the network stack will automatically include IP header & UDP headers, etc.
But since you are trying to create your own IP and UDP headers you must create a raw socket, then send the packet (and also calculate the checksum as your reference code is doing).
To create a raw socket, use socket(AF_INET, SOCK_RAW, 0)
.
Upvotes: 2
Reputation: 409462
Besides the problem with not using raw sockets, you also don't set e.g. port numbers correctly. The have to be in network byte-order, so you should use e.g. htons
for that. There are also other fields that should be in network byte orders.
Upvotes: 1