5

For a non-blocking datagram socket, like UDP, when I call write()/send() on the socket, each call of write()/send() or read()/recv() deals with exactly 1 packet.

I'm wondering if a raw socket, like the below, is a datagram socket or not?

int on = 1;
rawfd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
setsockopt(IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));
Patrick Yoder
  • 1,065
  • 4
  • 14
  • 19
user1944267
  • 1,557
  • 5
  • 20
  • 27

2 Answers2

2

That depends on the kind of IP header you will include in your packets (TCP or UDP). Actually it's more easier to include the UDP header since the kernel will manage some TCP mechanism.

So you have to add the UDP header in your packets, then it will be a datagram socket.

nouney
  • 4,363
  • 19
  • 31
  • it is raw socket, so TCP stack will not be involved. I think for raw socket, the TCP packet is just a packet, the TCP mechanism is not involved, isn/t it? – user1944267 Jun 17 '13 at 11:21
  • The mechanism is involved. The kernel do some stuff for you in the case of TCP sockets. Take a look at [this question](http://stackoverflow.com/questions/4323764/can-i-create-a-listening-tcp-socket-using-raw-sockets-in-linux). – nouney Jun 17 '13 at 12:03
  • ah, ok, it is for recv()/read() because the TCP stack will respond a incoming tcp packet. but for send()/write(), raw socket has nothing to do with local tcp stack. – user1944267 Jun 17 '13 at 13:01
  • I thought you need to receive and send :) It doesn't matter : you can use your raw socket as a datagram socket. – nouney Jun 17 '13 at 13:04
  • so you meant for raw socket, if I use it to send a tcp packet, it is operating like a datagram socket, right? – user1944267 Jun 17 '13 at 13:10
  • No, I mean you should only use the UDP header with raw sockets. The `send()` of a TCP raw socket may be fine, but you're not sure about the `recv()` (except if you manage the tcp stack yourself). – nouney Jun 17 '13 at 13:25
2

When you send data out, TCP/IP stack will add TCP/UDP header, IP header and then Ethernet header, and network work card transmit the whole packet out. For raw socket, you prepare all the headers(TCP/UDP, IP and MAC), and network work card transmit the whole packet out. So whether it is datagram depends on the header you add is TCP or UDP.

Hardy Feng
  • 459
  • 4
  • 13