简体   繁体   中英

What's the difference between Linux SOCK_RAW and SOCK_STREAM?

I've been studying networking with c code and cryptography lately and upon pondering random questions I stumbled across a block of code that's used for packet sniffing and I had a question on the actual socket that gets used in the function recvfrom() . The socket gets initialized through the following sock function rawSock = socket(AF_INET, SOCK_RAW, 0) .

I understand that SOCK_STREAM and SOCK_RAW are macros that represent an integer; but the question isn't about the values, it's about the results.

When would I use SOCK_STREAM over SOCK_RAW and vice versa?

I understand basic client and server communications using SOCK_STREAM . I'm working with C and in Linux

Read the man page .

For the prototype

int socket(int domain, int type, int protocol);

The types can be

   SOCK_STREAM     Provides sequenced, reliable, two-way, connection-
                   based byte streams.  An out-of-band data transmission
                   mechanism may be supported.

or

   SOCK_RAW        Provides raw network protocol access.

In one line, SOCK_STREAM is for connection oriented sockets, where the underlying OS creates and manages the headers for L4 (TCP), L3 and L2. OTOH SOCK_RAW provides more fine-grained control over header and packet construction, where the user has to construct and supply the headers and can also manage the contents.

To elaborate:

Sockets of type SOCK_STREAM are full-duplex byte streams. They do not preserve record boundaries. A stream socket must be in a connected state before any data may be sent or received on it. A connection to another socket is created with a connect(2) call. Once connected, data may be transferred using read(2) and write(2) calls or some variant of the send(2) and recv(2) calls. When a session has been completed a close(2) may be performed. Out-of-band data may also be transmitted as described in send(2) and received as described in recv(2).

and

SOCK_RAW sockets allow sending of datagrams to correspondents named in sendto(2) calls. Datagrams are generally received with recvfrom(2), which returns the next datagram along with the address of its sender.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM