Arranging bytes in a packet
If I need to create a packet like this:
field 1: SOCKS protocol version, 1 byte
field 2: status, 1 byte:
fie开发者_开发问答ld 3: reserved, must be 0x00
field 4: address type, 1 byte:
field 5: destination address of
1 byte of name length followed by the name for Domain name
field 6: network byte order port number, 2 bytes
char packet[6];
packet[0] = 5;
packet[1] = 0;
packet[2] = 0;
packet[3] = 1;
packet[4] = /* ... ???? ... */;
packet[5] = 80;`
How do I write the packet[4]
(field 5) for www.google.com
? Thanks in advance.
Well, you need more than six bytes, certainly. One straightforward option is to use a std::vector
:
std::vector<unsigned char> v;
v.push_back(5);
v.push_back(0);
v.push_back(0);
v.push_back(1);
std::string address = "www.google.com";
v.push_back(address.size());
std::copy(address.begin(), address.end(), std::back_inserter(v));
v.push_back(80);
// data is accessible as an array by using &v[0]
In order to have what you want you can't have each field as a specific fixed index in the packet array because each position can only hold atmost one byte. You'd have to do something like this:
char address[] = "www.google.com";
int addressLen = strlen(address);
char* packet = (char *) malloc(sizeof(char)*6+addressLen);
int i;
packet[0] = 5;
...
packet[3] = 1;
packet[4] = addressLen;
for (i = 0; i < addressLen; i++)
packet[i + 5] = address[i];
packet[4 + addressLen] = 80;
EDIT: Actually I made this example for C. Should work in C++ aswell but I don't know the interface of the network library you're using. That malloc probably could be replaced by a new. Or you could use the standard containers since I think those can be accessed as an array aswell.
精彩评论