IP(4)
π IP(4) π
okay bestie, so this is the manual page for ip β the Internet Protocol β straight outta the Kernel Interfaces Manual. it's a long one, so buckle up. part 1 starts rn π«Ά
β¨ NAME β¨
ip β Internet Protocol π
π SYNOPSIS π
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int
socket(AF_INET, SOCK_RAW, proto);
π¦ DESCRIPTION π¦
okay so IP is the transport layer protocol that the Internet protocol family rides on. you can set options at the IP level while using higher-level protocols that are based on IP (think TCP and UDP, bestie). you can also reach it through a βraw socketβ when you're out here developing brand new protocols, or building special-purpose applications. main character energy, honestly.
there are several IP-level setsockopt(2) and getsockopt(2) options. let's get into them π
IP_OPTIONS can be used to provide IP options to be transmitted in the IP header of each outgoing packet, or to examine the header options on incoming packets. IP options may be used with any socket type in the Internet family. the format of IP options to be sent is the one specified by the IP protocol specification (RFC-791), with exactly one exception: the list of addresses for Source Route options must include the first-hop gateway at the beginning of the list of gateways. that first-hop gateway address gets extracted from the option list and the size adjusted accordingly before use. to disable previously specified options, use a zero-length buffer:
setsockopt(s, IPPROTO_IP, IP_OPTIONS, NULL, 0);
IP_TOS and IP_TTL can be used to set the type-of-service and time-to-live fields in the IP header for SOCK_STREAM, SOCK_DGRAM, and certain types of SOCK_RAW sockets. for example:
int tos = IPTOS_LOWDELAY; /* see <netinet/ip.h> */
setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
int ttl = 60; /* max = 255 */
setsockopt(s, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
IP_MINTTL can be used to set the minimum acceptable TTL a packet must have when received on a socket. all packets with a lower TTL are silently dropped π. this option is only really useful when set to 255, preventing packets from outside the directly connected networks from reaching local listeners on sockets. no cap.
IP_DONTFRAG can be used to set the Don't Fragment flag on IP packets. currently this option is respected only on udp(4) and raw ip sockets, unless the IP_HDRINCL option has been set. on tcp(4) sockets, the Don't Fragment flag is controlled by the Path MTU Discovery option. sending a packet larger than the MTU size of the egress interface β determined by the destination address β returns an EMSGSIZE error. rude but okay.
if the IP_ORIGDSTADDR option is enabled on a SOCK_DGRAM socket, the recvmsg(2) call will return the destination IP address and destination port for a UDP datagram. the msg_control field in the msghdr structure points to a buffer that contains a cmsghdr structure followed by the sockaddr_in structure. the cmsghdr fields have these values:
cmsg_len = CMSG_LEN(sizeof(struct sockaddr_in))
cmsg_level = IPPROTO_IP
cmsg_type = IP_ORIGDSTADDR
if the IP_RECVDSTADDR option is enabled on a SOCK_DGRAM socket, the recvmsg(2) call will return the destination IP address for a UDP datagram. the msg_control field in the msghdr structure points to a buffer that contains a cmsghdr structure followed by the IP address. the cmsghdr fields have these values:
cmsg_len = CMSG_LEN(sizeof(struct in_addr))
cmsg_level = IPPROTO_IP
cmsg_type = IP_RECVDSTADDR
the source address to be used for outgoing UDP datagrams on a socket can be specified as ancillary data with a type code of IP_SENDSRCADDR. the msg_control field in the msghdr structure should point to a buffer that contains a cmsghdr structure followed by the IP address. the cmsghdr fields should have these values:
cmsg_len = CMSG_LEN(sizeof(struct in_addr))
cmsg_level = IPPROTO_IP
cmsg_type = IP_SENDSRCADDR
okay so the socket should be either bound to INADDR_ANY and a local port, and the address supplied with IP_SENDSRCADDR shouldn't be INADDR_ANY β or the socket should be bound to a local address and the address supplied with IP_SENDSRCADDR should be INADDR_ANY. in that latter case the bound address gets overridden via generic source address selection logic, which would choose the IP address of the interface closest to the destination. slay, honestly β¨
for convenience, IP_SENDSRCADDR is defined to have the same value as IP_RECVDSTADDR, so the IP_RECVDSTADDR control message from recvmsg(2) can be used directly as a control message for sendmsg(2). reusing, recycling, iconic behavior π
if the IP_ONESBCAST option is enabled on a SOCK_DGRAM or a SOCK_RAW socket, the destination address of outgoing broadcast datagrams on that socket will be forced to the undirected broadcast address, INADDR_BROADCAST, before transmission. this is in contrast to the default behavior of the system, which is to transmit undirected broadcasts via the first network interface with the IFF_BROADCAST flag set.
this option allows applications to choose which interface is used to transmit an undirected broadcast datagram. for example, the following code would force an undirected broadcast to be transmitted via the interface configured with the broadcast address 192.168.2.255:
char msg[512];
struct sockaddr_in sin;
int onesbcast = 1; /* 0 = disable (default), 1 = enable */
setsockopt(s, IPPROTO_IP, IP_ONESBCAST, &onesbcast, sizeof(onesbcast));
sin.sin_addr.s_addr = inet_addr("192.168.2.255");
sin.sin_port = htons(1234);
sendto(s, msg, sizeof(msg), 0, &sin, sizeof(sin));
it is the application's responsibility to set theIP_TTLoption to an appropriate value in order to prevent broadcast storms. βοΈ the application must have sufficient credentials to set theSO_BROADCASTsocket level option, otherwise theIP_ONESBCASToption has no effect.
if the IP_BINDANY option is enabled on a SOCK_STREAM, SOCK_DGRAM or a SOCK_RAW socket, you can bind(2) to any address, even one that isn't bound to any available network interface in the system. this functionality (in conjunction with special firewall rules) can be used for implementing a transparent proxy. the PRIV_NETINET_BINDANY privilege is needed to set this option. π
if the IP_RECVTTL option is enabled on a SOCK_DGRAM socket, the recvmsg(2) call will return the IP TTL (time to live) field for a UDP datagram. the msg_control field in the msghdr structure points to a buffer that contains a cmsghdr structure followed by the TTL. the cmsghdr fields have these values:
cmsg_len = CMSG_LEN(sizeof(u_char))
cmsg_level = IPPROTO_IP
cmsg_type = IP_RECVTTL
if the IP_RECVTOS option is enabled on a SOCK_DGRAM socket, the recvmsg(2) call will return the IP TOS (type of service) field for a UDP datagram. the msg_control field in the msghdr structure points to a buffer that contains a cmsghdr structure followed by the TOS. the cmsghdr fields have these values:
cmsg_len = CMSG_LEN(sizeof(u_char))
cmsg_level = IPPROTO_IP
cmsg_type = IP_RECVTOS
if the IP_RECVIF option is enabled on a SOCK_DGRAM socket, the recvmsg(2) call returns a struct sockaddr_dl corresponding to the interface on which the packet was received. the msg_control field in the msghdr structure points to a buffer that contains a cmsghdr structure followed by the struct sockaddr_dl. the cmsghdr fields have these values:
cmsg_len = CMSG_LEN(sizeof(struct sockaddr_dl))
cmsg_level = IPPROTO_IP
cmsg_type = IP_RECVIF
IP_PORTRANGE can be used to set the port range used for selecting a local port number on a socket with an unspecified (zero) port number. it has the following possible values:
IP_PORTRANGE_DEFAULTβ use the default range of values, normallyIPPORT_HIFIRSTAUTOthroughIPPORT_HILASTAUTO. this is adjustable through the sysctl setting:net.inet.ip.portrange.firstandnet.inet.ip.portrange.last.IP_PORTRANGE_HIGHβ use a high range of values, normallyIPPORT_HIFIRSTAUTOandIPPORT_HILASTAUTO. this is adjustable through the sysctl setting:net.inet.ip.portrange.hifirstandnet.inet.ip.portrange.hilast.IP_PORTRANGE_LOWβ use a low range of ports, which are normally restricted to privileged processes on Unix systems. the range is normally fromIPPORT_RESERVED - 1down toIPPORT_RESERVEDSTARTin descending order. this is adjustable through the sysctl setting:net.inet.ip.portrange.lowfirstandnet.inet.ip.portrange.lowlast.
the range of privileged ports which only may be opened by root-owned processes may be modified by the net.inet.ip.portrange.reservedlow and net.inet.ip.portrange.reservedhigh sysctl settings. the values default to the traditional range, 0 through IPPORT_RESERVED - 1 (0 through 1023), respectively. note that these settings do not affect and are not accounted for in the use or calculation of the other net.inet.ip.portrange values above.
changing these values departs from Unix tradition and has security consequences that the administrator should carefully evaluate before modifying these settings. π¨
ports are allocated at random within the specified port range in order to increase the difficulty of random spoofing attacks. in scenarios such as benchmarking, this behavior may be undesirable. in these cases, net.inet.ip.portrange.randomized can be used to toggle randomization off. if more than net.inet.ip.portrange.randomcps ports have been allocated in the last second, then return to sequential port allocation. return to random allocation only once the current port allocation rate drops below net.inet.ip.portrange.randomcps for at least net.inet.ip.portrange.randomtime seconds. the default values for net.inet.ip.portrange.randomcps and net.inet.ip.portrange.randomtime are 10 port allocations per second and 45 seconds correspondingly. β±οΈ
π Multicast Options π
IP multicasting is supported only on AF_INET sockets of type SOCK_DGRAM and SOCK_RAW, and only on networks where the interface driver supports multicasting. strict queen π
the IP_MULTICAST_TTL option changes the time-to-live (TTL) for outgoing multicast datagrams in order to control the scope of the multicasts:
u_char ttl; /* range: 0 to 255, default = 1 */
setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
datagrams with a TTL of 1 are not forwarded beyond the local network. multicast datagrams with a TTL of 0 will not be transmitted on any network, but may be delivered locally if the sending host belongs to the destination group and if multicast loopback has not been disabled on the sending socket (see below). multicast datagrams with TTL greater than 1 may be forwarded to other networks if a multicast router is attached to the local network. π
ok so if your host has multiple interfaces and you never specified which one for a multicast group membership? every multicast transmission just gets yeeted out of the primary network interface by default. the IP_MULTICAST_IF option is the vibe override for subsequent transmissions from a given socket:
struct in_addr addr;
setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));
where addr is the local IP address of the interface you actually want, or INADDR_ANY if you want the default interface. π«
Wanna specify the interface by index instead? pass an instance of ip_mreqn instead, bestie. set the imr_ifindex member to the index of the interface you want, or 0 for the default. the kernel tells these two structures apart by their size, iconic behavior honestly.
π¨ ngl, the use ofIP_MULTICAST_IFis not recommended, because multicast memberships are scoped to each individual interface. it's supported for legacy use only by applications like routing daemons that expect to be able to transmit link-local IPv4 multicast datagrams (224.0.0.0/24) on multiple interfaces without requesting an individual membership for each one. likeβ¦ it's giving legacy. π΅
You can grab an interface's local IP address and multicast capability via the SIOCGIFCONF and SIOCGIFFLAGS ioctls. normal applications should not need this option, fr fr.
β¨ loopback tea β¨ if a multicast datagram gets sent to a group that the sending host itself belongs to (on the outgoing interface), then by default a copy of the datagram is looped back by the IP layer for local delivery. the IP_MULTICAST_LOOP option hands the sender explicit control over whether subsequent datagrams get looped back or not:
u_char loop; /* 0 = disable, 1 = enable (default) */
setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
this one is a performance glow-up for apps that have no more than one instance on a single host (think: a routing daemon), because it eliminates the overhead of receiving their own transmissions. π«Ά but it should generally not be used by apps where there might be more than one instance on a single host (like a conferencing program), or where the sender doesn't belong to the destination group (like a time querying program).
the sysctl setting net.inet.ip.mcast.loop controls the default setting of the IP_MULTICAST_LOOP socket option for new sockets. πΈ
Also important, bestie: a multicast datagram sent with an initial TTL greater than 1 may be delivered to the sending host on a different interface from the one it was sent on, if the host belongs to the destination group on that other interface. and the loopback control option has no effect on that kind of delivery. π
A host has to become a member of a multicast group before it can receive datagrams sent to that group. to join one, you use IP_ADD_MEMBERSHIP:
struct ip_mreqn mreqn;
setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreqn, sizeof(mreqn));
where mreqn is this structure right here:
struct ip_mreqn {
struct in_addr imr_multiaddr; /* IP multicast address of group */
struct in_addr imr_interface; /* local IP address of interface */
int imr_ifindex; /* interface index */
}
imr_ifindex should be set to the index of a particular multicast-capable interface if the host is multihomed. if imr_ifindex is non-zero, the value of imr_interface gets ignored. otherwise, if imr_ifindex is 0, the kernel will use the IP address from imr_interface to look up the interface. you may set imr_interface to INADDR_ANY to choose the default interface, although this is not recommended β this is considered to be the first interface corresponding to the default route. otherwise, the first multicast-capable interface configured in the system gets used.
The legacy struct ip_mreq, which lacks the imr_ifindex field, is also supported by the IP_ADD_MEMBERSHIP setsockopt. in that case the kernel behaves as if imr_ifindex was set to zero: imr_interface will be used to look up the interface. π§
π°οΈ history lesson: prior toFreeBSD 7.0, if theimr_interfacemember was within the network range0.0.0.0/8, it was treated as an interface index in the system interface MIB, as per the RIP Version 2 MIB Extension (RFC-1724). in versions of FreeBSD since7.0, this behavior is no longer supported. developers should use the RFC 3678 multicast source filter APIs instead β in particular,MCAST_JOIN_GROUP.
Up to IP_MAX_MEMBERSHIPS memberships may be added on a single socket. membership is associated with a single interface, so programs running on multihomed hosts may need to join the same group on more than one interface. β¨
To drop a membership, you do:
struct ip_mreq mreq;
setsockopt(s, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
where mreq contains the same values you used to add the membership. and heads up β memberships get dropped automatically when the socket is closed or the process exits. π
β οΈ the IGMP lore β οΈ the IGMP protocol uses the primary IP address of the interface as its identifier for group membership. that's the first IP address configured on the interface. if this address is removed or changed, the results are undefined, because the IGMP membership state will then be inconsistent. and if multiple IP aliases are configured on the same interface, they will be ignored. π
This shortcoming was addressed in IPv6; MLDv2 requires that the unique link-local address for an interface is used to identify an MLDv2 listener. slay, IPv6. π
β¨ Source-Specific Multicast Options β¨
Since FreeBSD 8.0, the use of Source-Specific Multicast (SSM) is supported. these extensions need an IGMPv3 multicast router in order to make the best use of them. if a legacy multicast router is present on the link, FreeBSD will simply downgrade to the version of IGMP spoken by the router, and the benefits of source filtering on the upstream link will not be present β although the kernel will continue to squelch transmissions from blocked sources. π€«
Every group membership on a socket now has a filter mode:
MCAST_EXCLUDEβ datagrams sent to this group are accepted, unless the source is in a list of blocked source addresses.MCAST_INCLUDEβ datagrams sent to this group are accepted only if the source is in a list of accepted source addresses.
Groups joined using the legacy IP_ADD_MEMBERSHIP option are placed in exclusive-mode, and are able to request that certain sources are blocked or allowed. this is known as the delta-based API. π¦
To block a multicast source on an existing group membership:
struct ip_mreq_source mreqs;
setsockopt(s, IPPROTO_IP, IP_BLOCK_SOURCE, &mreqs, sizeof(mreqs));
where mreqs is this structure:
struct ip_mreq_source {
struct in_addr imr_multiaddr; /* IP multicast address of group */
struct in_addr imr_sourceaddr; /* IP address of source */
struct in_addr imr_interface; /* local IP address of interface */
}
imr_sourceaddr should be set to the address of the source to be blocked. π«
To unblock a multicast source on an existing group:
struct ip_mreq_source mreqs;
setsockopt(s, IPPROTO_IP, IP_UNBLOCK_SOURCE, &mreqs, sizeof(mreqs));
theIP_BLOCK_SOURCEandIP_UNBLOCK_SOURCEoptions are not permitted for inclusive-mode group memberships.
To join a multicast group in MCAST_INCLUDE mode with a single source, or to add another source to an existing inclusive-mode membership:
struct ip_mreq_source mreqs;
setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, &mreqs, sizeof(mreqs));
To leave a single source from an existing group in inclusive mode:
struct ip_mreq_source mreqs;
setsockopt(s, IPPROTO_IP, IP_DROP_SOURCE_MEMBERSHIP, &mreqs, sizeof(mreqs));
and if this is the last accepted source for the group, the membership gets dropped. periodt. π
theIP_ADD_SOURCE_MEMBERSHIPandIP_DROP_SOURCE_MEMBERSHIPoptions are not accepted for exclusive-mode group memberships. however, both exclusive and inclusive mode memberships support the use of the full-state API documented inRFC 3678. for management of source filter lists using this API, please refer tosourcefilter(3). π
The sysctl settings net.inet.ip.mcast.maxsocksrc and net.inet.ip.mcast.maxgrpsrc are used to specify an upper limit on the number of per-socket and per-group source filter entries which the kernel may allocate. π
β¨ Raw IP Sockets β¨
Raw IP sockets are connectionless, and are normally used with the sendto(2) and recvfrom(2) calls β though the connect(2) call may also be used to fix the destination for future packets (in which case the read(2) or recv(2) and write(2) or send(2) system calls may be used). π
If proto is 0, the default protocol IPPROTO_RAW is used for outgoing packets, and only incoming packets destined for that protocol are received. if proto is non-zero, that protocol number will be used on outgoing packets and to filter incoming packets.
Outgoing packets automatically have an IP header prepended to them (based on the destination address and the protocol number the socket is created with), unless the IP_HDRINCL option has been set. and unlike in previous BSD releases, incoming packets are received with the IP header and options intact, leaving all fields in network byte order. π
IP_HDRINCL indicates the complete IP header is included with the data and may be used only with the SOCK_RAW type.
#include <netinet/in_systm.h>
#include <netinet/ip.h>
int hincl = 1; /* 1 = on, 0 = off */
setsockopt(s, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl));
Unlike previous BSD releases, the program must set all the fields of the IP header, including the following:
ip->ip_v = IPVERSION;
ip->ip_hl = hlen >> 2;
ip->ip_id = 0; /* 0 means kernel set appropriate value */
ip->ip_off = htons(offset);
ip->ip_len = htons(len);
The packet should be provided as is to be sent over wire. this implies all fields, including ip_len and ip_off, need to be in network byte order. see byteorder(3) for more info on network byte order. π§
And two lil magic tricks, bestie: if the ip_id field is set to 0, then the kernel will choose an appropriate value. and if the header source address is set to INADDR_ANY, the kernel will choose an appropriate address. β¨
π ERRORS π
ok so sometimes things just go wrong, bestie. when a socket operation flops, it hands you back one of these:
[EISCONN]β you tried to set up a connection on a socket that already has one, or you tried to send a datagram with the destination address specified while the socket was already connected. pick a struggle, honestly π[ENOTCONN]β you tried to send a datagram but no destination address was specified, and the socket was never connected in the first place. it's giving "sent to nobody" π«₯[ENOBUFS]β the system ran out of memory for an internal data structure. not her fault, the vibes were just too much for the RAM π§[EADDRNOTAVAIL]β you tried to create a socket with a network address for which no network interface exists. that address? literally not a real place π[EACCES]β a non-privileged process tried to create a raw IP socket. sorry bestie, that's a VIP-only section π
now the β¨IP-specificβ¨ ones, which show up when you're setting or getting IP options:
[EINVAL]β an unknown socket option name was given. we don't know her π[EINVAL]β the IP option field was improperly formed: an option field was shorter than the minimum value, or longer than the option buffer provided. too short, too long, never just right π
and these ones can pop up when you're attempting to send IP datagrams via a "raw socket" with the IP_HDRINCL option set:
[EINVAL]β the user-suppliedip_lenfield was not equal to the length of the datagram written to the socket. the math was not mathing π₯
π¦ SEE ALSO π¦
go read your sisters, bestie, they're all iconic:
getsockopt(2)recv(2)send(2)byteorder(3)CMSG_DATA(3)sourcefilter(3)icmp(4)igmp(4)inet(4)intro(4)multicast(4)
and for the academic girlies: D. Thaler, B. Fenner, and B. Quinn, Socket Interface Extensions for Multicast Source Filters, RFC 3678, Jan 2004. no cap, that's the source material π
πΈ HISTORY πΈ
the ip protocol showed up in 4.2BSD. and the ip_mreqn structure? that one arrived later, in Linux 2.4. glow-ups take time π
π BUGS π
ok so these are the old-era quirks, and we're keeping receipts:
- Before FreeBSD 10.0, packets received on raw IP sockets had the
ip_hlsubtracted from theip_lenfield. yeah. just... subtracted it. no warning, no text, no call. π - Before FreeBSD 11.0, packets received on raw IP sockets had the
ip_lenandip_offfields converted to host byte order. and packets written to raw IP sockets were expected to haveip_lenandip_offin host byte order too. so if you're reading old code and the byte order looks sus, that's why π«
bestie, if you're dealing with anything pre-FreeBSD 11.0 on raw IP sockets, please check your byte order. i am begging. π₯Ί
and that's the whole page, periodt β¨ this one's from the Debian crew, dated May 24, 2020 β you were served IP(4), and she ate. mwah π π
π¦ where this page comes from
- debian bookworm: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- debian trixie: freebsd-manpages 12.2-2 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu jammy: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu noble: freebsd-manpages 12.2-1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu questing: freebsd-manpages 12.2-2
- ubuntu resolute: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- ubuntu stonking: freebsd-manpages 12.2-2build1 Β· BSD-2-Clause-FreeBSD AND BSD-4-Clause
- Copyright (c) 1983, 1991, 1993 The Regents of the University of California. All rights reserved
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms