1

I'm implementing a protocol in the linux kernel on top of UDP and want to send a reply from within the kernel when I receive a packet. For this, I want to run ip4_datagram_connect to get a route to the destination (which is the source address in the received packet) and then send a reply.

To call the ip4_datagram_connect, I need to fill in a sockaddr_in structure to pass as the address to the function. On comparing,

struct sockaddr_in

unsigned short   sin_port;           
struct in_addr   sin_addr;

struct udphdr

__be16 source;

and struct iphdr

__be32 saddr;

So my question is, do I need any helper function to copy the address and the port from the packet header into the sockaddr_in structure (like how we use htons etc. in socket programming)?

1 Answer 1

2

The value in the raw IP and UDP header are already in network byte order. The be in e.g. __be16 stands for "Big Endian", which is network byte order. The numbers in __be16 and __be32 is the number of bits.

The fields in the sockadd_in structures are also supposed to be in network byte order. The name htons stands for "Host To Network Short", i.e. it converts a short (which usually is 16 bits) from host byte order to network byte order.

So to answer your question: No, you do not need to do anything, plain assignment to sin_port and sin_addr.s_addr should be enough.

1
  • Thank you, I'll try it and then report here :) Jul 7, 2016 at 13:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.