How to set the format of a udp packet?
In an assignment it was required to form an ad hoc network between 2 laptops by switching the wireless LAN card in 2 laptops to the ad hoc m开发者_开发知识库ode then choosing a suitable SSID. I've created an adhock network between labtops. It was then required to Develop a “Sender” and a “Receiver” application to send a simple “Hello World" message from one laptop and receive it on the other one using sockets. I did it successfully using udp datagram sockets and udp packets (in java) as there is no server in adhoc networks. The only problem is that it was stated that packet format should look like the following, where data is represented as an array of bytes of maximum length = 64 KB (assume IP address is presented in 2 bytes):
| | | | | | | | | | | |H|E|L|L|O| |W|O|R|L|D|
__________|___________|
Sender ID |Reciever ID| data
(4 bytes) (4 bytes)
I know that at the reciver side you can get the address of the sent packet using packet.getAddress(); and the address of the reciever side is already known but I dnt understand the purpose of this format or how to set the format of a packet. I just wanna know what is the actual format of a udp packet and how to set the format of udp packet in java. How does creating a dataGram packet by specifying a buffer byte array, the intelAddress and the port sets the format of the packet? Do i need to modify the buffer byte array to be of the same format as stated above (although the address of the sender is sent anyways) ? Please reply to me as soon as you can. Any help will be appreciated. Thanks in advance.
The UDP packet has an implied format. http://en.wikipedia.org/wiki/User_Datagram_Protocol Java will take care of the 8 header bytes that must be there (source port, destination port, length, checksum). Even if you provide only a single byte of data, the 8 byte header will still be correctly created by Java. You are not responsible for forming those headers, only in providing the values that go in them.
All you have control of is the Data section of the packet. That can be formatted any way you like. It sounds like you are required to format it as you have shown above. The value of the that format may be debatable (source, destination addresses), but it sounds like you must adhere to it regardless.
Yes, you must modify the buffer byte array to be the same format as you provide. The other values (IP address and Port) are used either for forming the header, or actually sending the packet on the wire.
EDIT: Sorry, replaced 4 byte header with 8. My bad. You'd think I could read a protocol spec by now.
精彩评论