开发者

DHCP over UDP sending question

I am trying to make a simple DHCP client. It should send a message to DHCP server (already have this) receive a message back and parse it. I have created a struct

struct dhcp_msg{
 _int8 op;  //opcode
 _int8 htype; //hardware type
 _int8 haddr; //hardware adress
 _int8 hops;  //hop count

 _int32 tid;  //transaction id

 _int16 sec;  //seconds
 _int16 unused; //unused

 _int32 cipaddr;  //client ip
 _int32 yipaddr;  //your ip
 _int32 sipaddr;  //server ip
 _int32 gipaddr;  //gateway ip

 char chaddr[16]; //client hardware address
 char sname[64];  //server n开发者_如何学Pythoname
 char bname[128]; //boot file name

 _int8 mcookie[4];  //magic cookie
};

If I fill all fields with according data how to send this with sendto()? Should i parse it into char and send a pointer as sendto() requaries a pointer as a second parameter.

char *buffer;
...?
sendto(socketC, buffer, sizeof(buffer), 0, (SOCKADDR *)&servAddr, sizeof(sockaddr_in));

How to send this message?


First of all you must say to your compiler not to add any paddings into structures. And then you can do:

struct dhcp_msg my_msg;
// Fill my_msg
sendto(socket, (void *) &my_msg, ...)

UPDATE

In Linux and Windows sendto function are a bit different as we figured out in comments to this answer. So we should use (void *) and (char *) conversion for Linux and Windows respectively.

  • http://msdn.microsoft.com/en-us/library/ms740148%28v=vs.85%29.aspx
  • http://linux.die.net/man/2/sendto

About endianess: you should be also careful about it. But it should fork fine for all x86 CPUs. The only "wrong" endian style system I've ever used was a super computer based on IBM Power6.


You just need to pass the address of the buffer to sendto. No matter what type it will have - what really matters for sendto is the bytes there.

struct dhcp_msg msg;
// fill in all fields...
sendto(socketC, &msg, sizeof(struct dhcp_msg), ...);

The length of your message will be sizeof(struct dhcp_msg).

And don't forget that your compiler may add padding bytes to the struct, so its size may become bigger than you expect.


Let me start a new answer, as others have too much comments which are hard to dig in.

The problem which OP really has is a pointer type conversion error: MSVC refuses to pass struct dhcp_msg* as a const char* argument, and no explicit conversions help.

#include <sys/socket.h>

struct test {
    int a;
    int b;
};

int main() {
    struct test t;
    t.a = 3;
    t.b = 5;
    send(1, &t, sizeof(struct test), 0);

    return 0;
}

This source is not intended to be run, but it compiles fine with my GCC 4.4.5 (as well as void* and char* typecasting variants).

Ok, problem solved by doing typecasting carefully.


cast your struct dhcp_msg into a char*

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜