Skip to content

Add Protocol type and socket_with_protocol() for arbitrary protocol numbers#2733

Open
batkovic75 wants to merge 1 commit intonix-rust:masterfrom
batkovic75:add-eth-protocol-helper
Open

Add Protocol type and socket_with_protocol() for arbitrary protocol numbers#2733
batkovic75 wants to merge 1 commit intonix-rust:masterfrom
batkovic75:add-eth-protocol-helper

Conversation

@batkovic75
Copy link
Copy Markdown

Summary

Add a new Protocol type and socket_with_protocol() function that allow creating sockets with arbitrary protocol numbers not defined in the SockProtocol enum.

This is particularly useful for AF_PACKET sockets where Ethernet protocol numbers (like ETH_P_ARP, ETH_P_8021Q, etc.) need to be specified in network byte order.

New APIs

  • Protocol::new(c_int) - create from raw protocol number (all platforms)
  • Protocol::ethernet(u16) - create from Ethernet protocol with automatic byte order conversion (Linux/Android)
  • Protocol::as_raw() - get the raw value
  • socket_with_protocol() - like socket() but accepts Protocol
  • impl From<SockProtocol> for Protocol - convert existing protocols

Example

use nix::sys::socket::{socket_with_protocol, AddressFamily, SockType, SockFlag, Protocol};

// Create a raw socket to capture ARP packets
let proto = Protocol::ethernet(libc::ETH_P_ARP as u16);
let sock = socket_with_protocol(AddressFamily::Packet, SockType::Raw, SockFlag::empty(), proto)?;

Design Rationale

This takes an additive approach rather than modifying the existing SockProtocol enum:

  • Existing socket() API remains unchanged
  • No breaking changes
  • Users who need arbitrary protocols can opt-in to the new API

Related PRs took different approaches:

Closes #854

Test plan

  • Added test_protocol_ethernet test that verifies byte order conversion and socket creation
  • All existing tests pass
  • Clippy passes

Add a new `Protocol` type and `socket_with_protocol()` function that allow
creating sockets with arbitrary protocol numbers not defined in `SockProtocol`.

This is particularly useful for AF_PACKET sockets where Ethernet protocol
numbers (like ETH_P_ARP, ETH_P_802_1Q, etc.) need to be specified.

The `Protocol::ethernet()` helper automatically handles the conversion to
network byte order, which is required for Ethernet protocols.

Example usage:
```rust
let proto = Protocol::ethernet(libc::ETH_P_ARP as u16);
let sock = socket_with_protocol(
    AddressFamily::Packet,
    SockType::Raw,
    SockFlag::empty(),
    proto,
)?;
```
@batkovic75 batkovic75 force-pushed the add-eth-protocol-helper branch from 1c155d4 to 51e966f Compare January 30, 2026 13:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SockProtocol lacks protocols; No way to use ETH_P_ALL

1 participant