7

Correct me if I'm wrong, but my understanding of sending a raw packet inevitably is defined as buffering an array of bytes in an array, and writing it to a socket. However, most example code I've seen so far tend towards sendto, rarely is send used, and I've never seen code other than my own use write. Am I missing something? What is with this apparent preoccupation with complicating code like this?

Why use send and sendto when write seems to me to be the obvious choice when dealing with raw sockets?

psmears
  • 26,070
  • 4
  • 40
  • 48
motoku
  • 1,571
  • 1
  • 21
  • 49

1 Answers1

9

sendto is typically used with unconnected UDP sockets or raw sockets. It takes a parameter specifying the destination address/port of the packet. send and write don't have this parameter, so there's no way to tell the data where to go.

send is used with TCP sockets and connected UDP sockets. Since a connection has been established, a destination does not need to be specified, and in fact this function doesn't have a parameter for one.

While the write function can be used in places where send can be used, it lacks the flags parameter which can enable certain behaviors on TCP sockets. It also doesn't return the same set of error codes as send, so if things go wrong you might not get a meaningful error code. In theory you could also use write on a raw socket if the IP_HDRINCL socket option is set, but again it's not preferable since it doesn't support the same error codes as send.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    According to Posix (and a similar statement in linux and freebsd manpages), "If the socket argument refers to a socket and the flags argument is 0, the send() function is equivalent to write()." I think the only send-specific error are `ENOTSOCK` and `EOPNOTSUPP`, neither of which are relevant to `write`. – rici Feb 08 '16 at 23:32