출처: http://vallista.tistory.com/entry/Syntax-Highlighter-티스토리에서-코드-이쁘게-넣기 [VallistA]>

posted by ddanss 2018. 10. 19. 00:08
728x90

 * Kernel resident routing tables.
*
* The routing tables are initialized when interface addresses
* are set by making entries for all directly connected interfaces.
*/

/*
* A route consists of a destination address and a reference
* to a routing entry.  These are often held by protocols
* in their control blocks, e.g. inpcb.
*/
struct route {
struct rtentry *ro_rt;
struct sockaddr ro_dst;
};

/*
* These numbers are used by reliable protocols for determining
* retransmission behavior and are included in the routing structure.
*/
struct
rt_metrics {
u_long rmx_locks; /* Kernel must leave these values alone */
u_long rmx_mtu; /* MTU for this path */
u_long rmx_hopcount; /* max hops expected */
u_long rmx_expire; /* lifetime for route, e.g. redirect */
u_long rmx_recvpipe; /* inbound delay-bandwith product */
u_long rmx_sendpipe; /* outbound delay-bandwith product */
u_long rmx_ssthresh; /* outbound gateway buffer limit */
u_long rmx_rtt; /* estimated round trip time */
u_long rmx_rttvar; /* estimated rtt variance */
u_long rmx_pksent; /* packets sent using this route */
};

/*
* rmx_rtt and rmx_rttvar are stored as microseconds;
* RTTTOPRHZ(rtt) converts to a value suitable for use
* by a protocol slowtimo counter.
*/
#define
RTM_RTTUNIT 1000000 /* units for rtt, rttvar, as units per sec */
#define
RTTTOPRHZ(r) ((r) / (RTM_RTTUNIT / PR_SLOWHZ))

/*
* We distinguish between routes to hosts and routes to networks,
* preferring the former if available.  For each route we infer
* the interface to use from the gateway address supplied when
* the route was entered.  Routes that forward packets through
* gateways are marked so that the output routines know to address the
* gateway rather than the ultimate destination.
*/
#ifndef RNF_NORMAL
#include <net/radix.h>
#endif
struct
rtentry {
struct radix_node rt_nodes[2]; /* tree glue, and other values */
#define
rt_key(r) ((struct sockaddr *)((r)->rt_nodes->rn_key))
#define
rt_mask(r) ((struct sockaddr *)((r)->rt_nodes->rn_mask))
struct sockaddr *rt_gateway; /* value */
short rt_flags; /* up/down?, host/net */
short rt_refcnt; /* # held references */
u_long rt_use; /* raw # packets forwarded */
struct ifnet *rt_ifp; /* the answer: interface to use */
struct ifaddr *rt_ifa; /* the answer: interface to use */
struct sockaddr *rt_genmask; /* for generation of cloned routes */
caddr_t rt_llinfo; /* pointer to link level info cache */
struct rt_metrics rt_rmx; /* metrics used by rx'ing protocols */
struct rtentry *rt_gwroute; /* implied entry for gatewayed routes */
};

/*
* Following structure necessary for 4.3 compatibility;
* We should eventually move it to a compat file.
*/
struct
ortentry {
u_long rt_hash; /* to speed lookups */
struct sockaddr rt_dst; /* key */
struct sockaddr rt_gateway; /* value */
short rt_flags; /* up/down?, host/net */
short rt_refcnt; /* # held references */
u_long rt_use; /* raw # packets forwarded */
struct ifnet *rt_ifp; /* the answer: interface to use */
};

#define
RTF_UP 0x1 /* route useable */
#define
RTF_GATEWAY 0x2 /* destination is a gateway */
#define
RTF_HOST 0x4 /* host entry (net otherwise) */
#define
RTF_REJECT 0x8 /* host or net unreachable */
#define
RTF_DYNAMIC 0x10 /* created dynamically (by redirect) */
#define
RTF_MODIFIED 0x20 /* modified dynamically (by redirect) */
#define
RTF_DONE 0x40 /* message confirmed */
#define
RTF_MASK 0x80 /* subnet mask present */
#define
RTF_CLONING 0x100 /* generate new routes on use */
#define
RTF_XRESOLVE 0x200 /* external daemon resolves name */
#define
RTF_LLINFO 0x400 /* generated by ARP or ESIS */
#define
RTF_STATIC 0x800 /* manually added */
#define
RTF_BLACKHOLE 0x1000 /* just discard pkts (during updates) */
#define
RTF_PROTO2 0x4000 /* protocol specific routing flag */
#define
RTF_PROTO1 0x8000 /* protocol specific routing flag */


/*
* Routing statistics.
*/
struct
rtstat {
short rts_badredirect; /* bogus redirect calls */
short rts_dynamic; /* routes created by redirects */
short rts_newgateway; /* routes modified by redirects */
short rts_unreach; /* lookups which failed */
short rts_wildcard; /* lookups satisfied by a wildcard */
};
/*
* Structures for routing messages.
*/
struct
rt_msghdr {
u_short rtm_msglen; /* to skip over non-understood messages */
u_char rtm_version; /* future binary compatability */
u_char rtm_type; /* message type */
u_short rtm_index; /* index for associated ifp */
int rtm_flags; /* flags, incl. kern & message, e.g. DONE */
int rtm_addrs; /* bitmask identifying sockaddrs in msg */
pid_t rtm_pid; /* identify sender */
int rtm_seq; /* for sender to identify action */
int rtm_errno; /* why failed */
int rtm_use; /* from rtentry */
u_long rtm_inits; /* which metrics we are initializing */
struct rt_metrics rtm_rmx; /* metrics themselves */
};

#define
RTM_VERSION 3 /* Up the ante and ignore older versions */

#define
RTM_ADD 0x1 /* Add Route */
#define
RTM_DELETE 0x2 /* Delete Route */
#define
RTM_CHANGE 0x3 /* Change Metrics or flags */
#define
RTM_GET 0x4 /* Report Metrics */
#define
RTM_LOSING 0x5 /* Kernel Suspects Partitioning */
#define
RTM_REDIRECT 0x6 /* Told to use different route */
#define
RTM_MISS 0x7 /* Lookup failed on this address */
#define
RTM_LOCK 0x8 /* fix specified metrics */
#define
RTM_OLDADD 0x9 /* caused by SIOCADDRT */
#define
RTM_OLDDEL 0xa /* caused by SIOCDELRT */
#define
RTM_RESOLVE 0xb /* req to resolve dst to LL addr */
#define
RTM_NEWADDR 0xc /* address being added to iface */
#define
RTM_DELADDR 0xd /* address being removed from iface */
#define
RTM_IFINFO 0xe /* iface going up/down etc. */

#define
RTV_MTU 0x1 /* init or lock _mtu */
#define
RTV_HOPCOUNT 0x2 /* init or lock _hopcount */
#define
RTV_EXPIRE 0x4 /* init or lock _hopcount */
#define
RTV_RPIPE 0x8 /* init or lock _recvpipe */
#define
RTV_SPIPE 0x10 /* init or lock _sendpipe */
#define
RTV_SSTHRESH 0x20 /* init or lock _ssthresh */
#define
RTV_RTT 0x40 /* init or lock _rtt */
#define
RTV_RTTVAR 0x80 /* init or lock _rttvar */

/*
* Bitmask values for rtm_addr.
*/
#define
RTA_DST 0x1 /* destination sockaddr present */
#define
RTA_GATEWAY 0x2 /* gateway sockaddr present */
#define
RTA_NETMASK 0x4 /* netmask sockaddr present */
#define
RTA_GENMASK 0x8 /* cloning mask sockaddr present */
#define
RTA_IFP 0x10 /* interface name sockaddr present */
#define
RTA_IFA 0x20 /* interface addr sockaddr present */
#define
RTA_AUTHOR 0x40 /* sockaddr for author of redirect */
#define
RTA_BRD 0x80 /* for NEWADDR, broadcast or p-p dest addr */

/*
* Index offsets for sockaddr array for alternate internal encoding.
*/
#define
RTAX_DST 0 /* destination sockaddr present */
#define
RTAX_GATEWAY 1 /* gateway sockaddr present */
#define
RTAX_NETMASK 2 /* netmask sockaddr present */
#define
RTAX_GENMASK 3 /* cloning mask sockaddr present */
#define
RTAX_IFP 4 /* interface name sockaddr present */
#define
RTAX_IFA 5 /* interface addr sockaddr present */
#define
RTAX_AUTHOR 6 /* sockaddr for author of redirect */
#define
RTAX_BRD 7 /* for NEWADDR, broadcast or p-p dest addr */
#define
RTAX_MAX 8 /* size of array to allocate */

struct
rt_addrinfo {
int rti_addrs;
struct sockaddr *rti_info[RTAX_MAX];
};

struct
route_cb {
int ip_count;
int ns_count;
int iso_count;
int any_count;
};

#ifdef KERNEL
#define
RTFREE(rt) \
if ((rt)->rt_refcnt <= 1) \
rtfree(rt); \
else \
(rt)->rt_refcnt--;

struct route_cb route_cb;
struct rtstat rtstat;
struct radix_node_head *
rt_tables[AF_MAX+1];

void route_init __P((void));
int route_output __P((struct mbuf *, struct socket *));
int route_usrreq __P((struct socket *,
    int, struct mbuf *, struct mbuf *, struct mbuf *));
void rt_ifmsg __P((struct ifnet *));
void rt_maskedcopy __P((struct sockaddr *,
    struct sockaddr *, struct sockaddr *));
void rt_missmsg __P((int, struct rt_addrinfo *, int, int));
void rt_newaddrmsg __P((int, struct ifaddr *, int, struct rtentry *));
int rt_setgate __P((struct rtentry *,
    struct sockaddr *, struct sockaddr *));
void rt_setmetrics __P((u_long, struct rt_metrics *, struct rt_metrics *));
void rtable_init __P((void **));
void rtalloc __P((struct route *));
struct rtentry *
rtalloc1 __P((struct sockaddr *, int));
void rtfree __P((struct rtentry *));
int rtinit __P((struct ifaddr *, int, int));
int rtioctl __P((int, caddr_t, struct proc *));
int rtredirect __P((struct sockaddr *, struct sockaddr *,
    struct sockaddr *, int, struct sockaddr *, struct rtentry **));
int rtrequest __P((int, struct sockaddr *,
    struct sockaddr *, struct sockaddr *, int, struct rtentry **));
#endif






반응형
posted by ddanss 2018. 10. 16. 15:45
728x90

NAME         top

       rtnetlink - macros to manipulate rtnetlink messages

SYNOPSIS         top

       #include <asm/types.h>
       #include <linux/netlink.h>
       #include <linux/rtnetlink.h>
       #include <sys/socket.h>

       rtnetlink_socket = socket(AF_NETLINK, int socket_type,
       NETLINK_ROUTE);

       int RTA_OK(struct rtattr *rta, int rtabuflen);

       void *RTA_DATA(struct rtattr *rta);

       unsigned int RTA_PAYLOAD(struct rtattr *rta);

       struct rtattr *RTA_NEXT(struct rtattr *rta, unsigned int rtabuflen);

       unsigned int RTA_LENGTH(unsigned int length);

       unsigned int RTA_SPACE(unsigned int length);

DESCRIPTION         top

       All rtnetlink(7) messages consist of a netlink(7) message header and
       appended attributes.  The attributes should be manipulated only using
       the macros provided here.

       RTA_OK(rta, attrlen) returns true if rta points to a valid routing
       attribute; attrlen is the running length of the attribute buffer.
       When not true then you must assume there are no more attributes in
       the message, even if attrlen is nonzero.

       RTA_DATA(rta) returns a pointer to the start of this attribute's
       data.

       RTA_PAYLOAD(rta) returns the length of this attribute's data.

       RTA_NEXT(rta, attrlen) gets the next attribute after rta.  Calling
       this macro will update attrlen.  You should use RTA_OK to check the
       validity of the returned pointer.

       RTA_LENGTH(len) returns the length which is required for len bytes of
       data plus the header.

       RTA_SPACE(len) returns the amount of space which will be needed in a
       message with len bytes of data.

CONFORMING TO         top

       These macros are nonstandard Linux extensions.

BUGS         top

       This manual page is incomplete.

EXAMPLE         top

       Creating a rtnetlink message to set the MTU of a device:

           #include <linux/rtnetlink.h>

           ...

           struct {
               struct nlmsghdr  nh;
               struct ifinfomsg if;
               char             attrbuf[512];
           } req;

           struct rtattr *rta;
           unsigned int mtu = 1000;

           int rtnetlink_sk = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);

           memset(&req, 0, sizeof(req));
           req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
           req.nh.nlmsg_flags = NLM_F_REQUEST;
           req.nh.nlmsg_type = RTM_NEWLINK;
           req.if.ifi_family = AF_UNSPEC;
           req.if.ifi_index = INTERFACE_INDEX;
           req.if.ifi_change = 0xffffffff; /* ??? */
           rta = (struct rtattr *)(((char *) &req) +
                                    NLMSG_ALIGN(req.nh.nlmsg_len));
           rta->rta_type = IFLA_MTU;
           rta->rta_len = RTA_LENGTH(sizeof(unsigned int));
           req.nh.nlmsg_len = NLMSG_ALIGN(req.nh.nlmsg_len) +
                                         RTA_LENGTH(sizeof(mtu));
           memcpy(RTA_DATA(rta), &mtu, sizeof(mtu));
           send(rtnetlink_sk, &req, req.nh.nlmsg_len, 0);
반응형
posted by ddanss 2018. 10. 16. 15:24
728x90

NAME         top

       netlink - communication between kernel and user space (AF_NETLINK)

SYNOPSIS         top

       #include <asm/types.h>
       #include <sys/socket.h>
       #include <linux/netlink.h>

       netlink_socket = socket(AF_NETLINK, socket_type, netlink_family);

DESCRIPTION         top

       Netlink is used to transfer information between the kernel and user-
       space processes.  It consists of a standard sockets-based interface
       for user space processes and an internal kernel API for kernel
       modules.  The internal kernel interface is not documented in this
       manual page.  There is also an obsolete netlink interface via netlink
       character devices; this interface is not documented here and is
       provided only for backward compatibility.

       Netlink is a datagram-oriented service.  Both SOCK_RAW and SOCK_DGRAM
       are valid values for socket_type.  However, the netlink protocol does
       not distinguish between datagram and raw sockets.

       netlink_family selects the kernel module or netlink group to
       communicate with.  The currently assigned netlink families are:

       NETLINK_ROUTE
              Receives routing and link updates and may be used to modify
              the routing tables (both IPv4 and IPv6), IP addresses, link
              parameters, neighbor setups, queueing disciplines, traffic
              classes and packet classifiers (see rtnetlink(7)).

       NETLINK_W1 (Linux 2.6.13 to 2.16.17)
              Messages from 1-wire subsystem.

       NETLINK_USERSOCK
              Reserved for user-mode socket protocols.

       NETLINK_FIREWALL (up to and including Linux 3.4)
              Transport IPv4 packets from netfilter to user space.  Used by
              ip_queue kernel module.  After a long period of being declared
              obsolete (in favor of the more advanced nfnetlink_queue
              feature), NETLINK_FIREWALL was removed in Linux 3.5.

       NETLINK_INET_DIAG (since Linux 2.6.14)
              Query information about sockets of various protocol families
              from the kernel (see sock_diag(7)).

       NETLINK_SOCK_DIAG (since Linux 3.3)
              A synonym for NETLINK_INET_DIAG.

       NETLINK_NFLOG (up to and including Linux 3.16)
              Netfilter/iptables ULOG.

       NETLINK_XFRM
              IPsec.

       NETLINK_SELINUX (since Linux 2.6.4)
              SELinux event notifications.

       NETLINK_ISCSI (since Linux 2.6.15)
              Open-iSCSI.

       NETLINK_AUDIT (since Linux 2.6.6)
              Auditing.

       NETLINK_FIB_LOOKUP (since Linux 2.6.13)
              Access to FIB lookup from user space.

       NETLINK_CONNECTOR (since Linux 2.6.14)
              Kernel connector.  See Documentation/connector/* in the Linux
              kernel source tree for further information.

       NETLINK_NETFILTER (since Linux 2.6.14)
              Netfilter subsystem.

       NETLINK_SCSITRANSPORT (since Linux 2.6.19)
              SCSI Transports.

       NETLINK_RDMA (since Linux 3.0)
              Infiniband RDMA.

       NETLINK_IP6_FW (up to and including Linux 3.4)
              Transport IPv6 packets from netfilter to user space.  Used by
              ip6_queue kernel module.

       NETLINK_DNRTMSG
              DECnet routing messages.

       NETLINK_KOBJECT_UEVENT (since Linux 2.6.10)
              Kernel messages to user space.

       NETLINK_GENERIC (since Linux 2.6.15)
              Generic netlink family for simplified netlink usage.

       NETLINK_CRYPTO (since Linux 3.2)
              Netlink interface to request information about ciphers
              registered with the kernel crypto API as well as allow
              configuration of the kernel crypto API.

       Netlink messages consist of a byte stream with one or multiple
       nlmsghdr headers and associated payload.  The byte stream should be
       accessed only with the standard NLMSG_* macros.  See netlink(3) for
       further information.

       In multipart messages (multiple nlmsghdr headers with associated
       payload in one byte stream) the first and all following headers have
       the NLM_F_MULTI flag set, except for the last header which has the
       type NLMSG_DONE.

       After each nlmsghdr the payload follows.

           struct nlmsghdr {
               __u32 nlmsg_len;    /* Length of message including header */
               __u16 nlmsg_type;   /* Type of message content */
               __u16 nlmsg_flags;  /* Additional flags */
               __u32 nlmsg_seq;    /* Sequence number */
               __u32 nlmsg_pid;    /* Sender port ID */
           };

       nlmsg_type can be one of the standard message types: NLMSG_NOOP mes‐
       sage is to be ignored, NLMSG_ERROR message signals an error and the
       payload contains an nlmsgerr structure, NLMSG_DONE message terminates
       a multipart message.

           struct nlmsgerr {
               int error;        /* Negative errno or 0 for acknowledgements */
               struct nlmsghdr msg;  /* Message header that caused the error */
           };

       A netlink family usually specifies more message types, see the appro‐
       priate manual pages for that, for example, rtnetlink(7) for
       NETLINK_ROUTE.

       Standard flag bits in nlmsg_flags
       ──────────────────────────────────────────────────────────
       NLM_F_REQUEST   Must be set on all request messages.
       NLM_F_MULTI     The message is part of a multipart mes‐
                       sage terminated by NLMSG_DONE.
       NLM_F_ACK       Request for an acknowledgment on success.
       NLM_F_ECHO      Echo this request.

       Additional flag bits for GET requests
       ────────────────────────────────────────────────────────────────────
       NLM_F_ROOT     Return the complete table instead of a single entry.
       NLM_F_MATCH    Return all entries matching criteria passed in mes‐
                      sage content.  Not implemented yet.
       NLM_F_ATOMIC   Return an atomic snapshot of the table.
       NLM_F_DUMP     Convenience macro; equivalent to
                      (NLM_F_ROOT|NLM_F_MATCH).

       Note that NLM_F_ATOMIC requires the CAP_NET_ADMIN capability or an
       effective UID of 0.

       Additional flag bits for NEW requests
       ────────────────────────────────────────────────────────────
       NLM_F_REPLACE   Replace existing matching object.
       NLM_F_EXCL      Don't replace if the object already exists.
       NLM_F_CREATE    Create object if it doesn't already exist.
       NLM_F_APPEND    Add to the end of the object list.

       nlmsg_seq and nlmsg_pid are used to track messages.  nlmsg_pid shows
       the origin of the message.  Note that there isn't a 1:1 relationship
       between nlmsg_pid and the PID of the process if the message origi‐
       nated from a netlink socket.  See the ADDRESS FORMATS section for
       further information.

       Both nlmsg_seq and nlmsg_pid are opaque to netlink core.

       Netlink is not a reliable protocol.  It tries its best to deliver a
       message to its destination(s), but may drop messages when an out-of-
       memory condition or other error occurs.  For reliable transfer the
       sender can request an acknowledgement from the receiver by setting
       the NLM_F_ACK flag.  An acknowledgment is an NLMSG_ERROR packet with
       the error field set to 0.  The application must generate acknowledge‐
       ments for received messages itself.  The kernel tries to send an
       NLMSG_ERROR message for every failed packet.  A user process should
       follow this convention too.

       However, reliable transmissions from kernel to user are impossible in
       any case.  The kernel can't send a netlink message if the socket buf‐
       fer is full: the message will be dropped and the kernel and the user-
       space process will no longer have the same view of kernel state.  It
       is up to the application to detect when this happens (via the ENOBUFS
       error returned by recvmsg(2)) and resynchronize.

   Address formats
       The sockaddr_nl structure describes a netlink client in user space or
       in the kernel.  A sockaddr_nl can be either unicast (only sent to one
       peer) or sent to netlink multicast groups (nl_groups not equal 0).

           struct sockaddr_nl {
               sa_family_t     nl_family;  /* AF_NETLINK */
               unsigned short  nl_pad;     /* Zero */
               pid_t           nl_pid;     /* Port ID */
               __u32           nl_groups;  /* Multicast groups mask */
           };

       nl_pid is the unicast address of netlink socket.  It's always 0 if
       the destination is in the kernel.  For a user-space process, nl_pid
       is usually the PID of the process owning the destination socket.
       However, nl_pid identifies a netlink socket, not a process.  If a
       process owns several netlink sockets, then nl_pid can be equal to the
       process ID only for at most one socket.  There are two ways to assign
       nl_pid to a netlink socket.  If the application sets nl_pid before
       calling bind(2), then it is up to the application to make sure that
       nl_pid is unique.  If the application sets it to 0, the kernel takes
       care of assigning it.  The kernel assigns the process ID to the first
       netlink socket the process opens and assigns a unique nl_pid to every
       netlink socket that the process subsequently creates.

       nl_groups is a bit mask with every bit representing a netlink group
       number.  Each netlink family has a set of 32 multicast groups.  When
       bind(2) is called on the socket, the nl_groups field in the sock‐
       addr_nl should be set to a bit mask of the groups which it wishes to
       listen to.  The default value for this field is zero which means that
       no multicasts will be received.  A socket may multicast messages to
       any of the multicast groups by setting nl_groups to a bit mask of the
       groups it wishes to send to when it calls sendmsg(2) or does a
       connect(2).  Only processes with an effective UID of 0 or the
       CAP_NET_ADMIN capability may send or listen to a netlink multicast
       group.  Since Linux 2.6.13, messages can't be broadcast to multiple
       groups.  Any replies to a message received for a multicast group
       should be sent back to the sending PID and the multicast group.  Some
       Linux kernel subsystems may additionally allow other users to send
       and/or receive messages.  As at Linux 3.0, the NETLINK_KOB‐
       JECT_UEVENT, NETLINK_GENERIC, NETLINK_ROUTE, and NETLINK_SELINUX
       groups allow other users to receive messages.  No groups allow other
       users to send messages.

   Socket options
       To set or get a netlink socket option, call getsockopt(2) to read or
       setsockopt(2) to write the option with the option level argument set
       to SOL_NETLINK.  Unless otherwise noted, optval is a pointer to an
       int.

       NETLINK_PKTINFO (since Linux 2.6.14)
              Enable nl_pktinfo control messages for received packets to get
              the extended destination group number.

       NETLINK_ADD_MEMBERSHIP, NETLINK_DROP_MEMBERSHIP (since Linux 2.6.14)
              Join/leave a group specified by optval.

       NETLINK_LIST_MEMBERSHIPS (since Linux 4.2)
              Retrieve all groups a socket is a member of.  optval is a
              pointer to __u32 and optlen is the size of the array.  The
              array is filled with the full membership set of the socket,
              and the required array size is returned in optlen.

       NETLINK_BROADCAST_ERROR (since Linux 2.6.30)
              When not set, netlink_broadcast() only reports ESRCH errors
              and silently ignore NOBUFS errors.

       NETLINK_NO_ENOBUFS (since Linux 2.6.30)
              This flag can be used by unicast and broadcast listeners to
              avoid receiving ENOBUFS errors.

       NETLINK_LISTEN_ALL_NSID (since Linux 4.2)
              When set, this socket will receive netlink notifications from
              all network namespaces that have an nsid assigned into the
              network namespace where the socket has been opened.  The nsid
              is sent to user space via an ancillary data.

       NETLINK_CAP_ACK (since Linux 4.2)
              The kernel may fail to allocate the necessary room for the
              acknowledgment message back to user space.  This option trims
              off the payload of the original netlink message.  The netlink
              message header is still included, so the user can guess from
              the sequence number which message triggered the acknowledg‐
              ment.

VERSIONS         top

       The socket interface to netlink first appeared Linux 2.2.

       Linux 2.0 supported a more primitive device-based netlink interface
       (which is still available as a compatibility option).  This obsolete
       interface is not described here.

NOTES         top

       It is often better to use netlink via libnetlink or libnl than via
       the low-level kernel interface.

BUGS         top

       This manual page is not complete.

EXAMPLE         top

       The following example creates a NETLINK_ROUTE netlink socket which
       will listen to the RTMGRP_LINK (network interface
       create/delete/up/down events) and RTMGRP_IPV4_IFADDR (IPv4 addresses
       add/delete events) multicast groups.

           struct sockaddr_nl sa;

           memset(&sa, 0, sizeof(sa));
           sa.nl_family = AF_NETLINK;
           sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;

           fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
           bind(fd, (struct sockaddr *) &sa, sizeof(sa));

       The next example demonstrates how to send a netlink message to the
       kernel (pid 0).  Note that the application must take care of message
       sequence numbers in order to reliably track acknowledgements.

           struct nlmsghdr *nh;    /* The nlmsghdr with payload to send */
           struct sockaddr_nl sa;
           struct iovec iov = { nh, nh->nlmsg_len };
           struct msghdr msg;

           msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
           memset(&sa, 0, sizeof(sa));
           sa.nl_family = AF_NETLINK;
           nh->nlmsg_pid = 0;
           nh->nlmsg_seq = ++sequence_number;
           /* Request an ack from kernel by setting NLM_F_ACK */
           nh->nlmsg_flags |= NLM_F_ACK;

           sendmsg(fd, &msg, 0);

       And the last example is about reading netlink message.

           int len;
           char buf[8192];     /* 8192 to avoid message truncation on
                                  platforms with page size > 4096 */
           struct iovec iov = { buf, sizeof(buf) };
           struct sockaddr_nl sa;
           struct msghdr msg;
           struct nlmsghdr *nh;

           msg = { &sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
           len = recvmsg(fd, &msg, 0);

           for (nh = (struct nlmsghdr *) buf; NLMSG_OK (nh, len);
                nh = NLMSG_NEXT (nh, len)) {
               /* The end of multipart message */
               if (nh->nlmsg_type == NLMSG_DONE)
                   return;

               if (nh->nlmsg_type == NLMSG_ERROR)
                   /* Do some error handling */
               ...

               /* Continue with parsing payload */
               ...
           }
반응형
posted by ddanss 2018. 10. 14. 23:07
728x90

출처는 linux man page요!

 

 

 

 

#include <asm/types.h>
       #include <linux/netlink.h>
       #include <linux/rtnetlink.h>
       #include <sys/socket.h>

       rtnetlink_socket = socket(AF_NETLINK, int socket_type,
       NETLINK_ROUTE);

DESCRIPTION         top

       Rtnetlink allows the kernel's routing tables to be read and altered.
       It is used within the kernel to communicate between various
       subsystems, though this usage is not documented here, and for
       communication with user-space programs.  Network routes, IP
       addresses, link parameters, neighbor setups, queueing disciplines,
       traffic classes and packet classifiers may all be controlled through
       NETLINK_ROUTE sockets.  It is based on netlink messages; see
       netlink(7) for more information.

   Routing attributes
       Some rtnetlink messages have optional attributes after the initial
       header:

           struct rtattr {
               unsigned short rta_len;    /* Length of option */
               unsigned short rta_type;   /* Type of option */
               /* Data follows */
           };

       These attributes should be manipulated using only the RTA_* macros or
       libnetlink, see rtnetlink(3).

   Messages
       Rtnetlink consists of these message types (in addition to standard
       netlink messages):

       RTM_NEWLINK, RTM_DELLINK, RTM_GETLINK
              Create, remove or get information about a specific network
              interface.  These messages contain an ifinfomsg structure fol‐
              lowed by a series of rtattr structures.

              struct ifinfomsg {
                  unsigned char  ifi_family; /* AF_UNSPEC */
                  unsigned short ifi_type;   /* Device type */
                  int            ifi_index;  /* Interface index */
                  unsigned int   ifi_flags;  /* Device flags  */
                  unsigned int   ifi_change; /* change mask */
              };

              ifi_flags contains the device flags, see netdevice(7);
              ifi_index is the unique interface index (since Linux 3.7, it
              is possible to feed a nonzero value with the RTM_NEWLINK mes‐
              sage, thus creating a link with the given ifindex); ifi_change
              is reserved for future use and should be always set to
              0xFFFFFFFF.

                                 Routing attributes

              rta_type         value type         description
              ──────────────────────────────────────────────────────────
              IFLA_UNSPEC      -                  unspecified.
              IFLA_ADDRESS     hardware address   interface L2 address
              IFLA_BROADCAST   hardware address   L2 broadcast address.
              IFLA_IFNAME      asciiz string      Device name.
              IFLA_MTU         unsigned int       MTU of the device.
              IFLA_LINK        int                Link type.
              IFLA_QDISC       asciiz string      Queueing discipline.
              IFLA_STATS       see below          Interface Statistics.

       The value type for IFLA_STATS is struct rtnl_link_stats (struct
       net_device_stats in Linux 2.4 and earlier).

       RTM_NEWADDR, RTM_DELADDR, RTM_GETADDR
              Add, remove or receive information about an IP address associ‐
              ated with an interface.  In Linux 2.2, an interface can carry
              multiple IP addresses, this replaces the alias device concept
              in 2.0.  In Linux 2.2, these messages support IPv4 and IPv6
              addresses.  They contain an ifaddrmsg structure, optionally
              followed by rtattr routing attributes.

              struct ifaddrmsg {
                  unsigned char ifa_family;    /* Address type */
                  unsigned char ifa_prefixlen; /* Prefixlength of address */
                  unsigned char ifa_flags;     /* Address flags */
                  unsigned char ifa_scope;     /* Address scope */
                  int           ifa_index;     /* Interface index */
              };

              ifa_family is the address family type (currently AF_INET or
              AF_INET6), ifa_prefixlen is the length of the address mask of
              the address if defined for the family (like for IPv4),
              ifa_scope is the address scope, ifa_index is the interface
              index of the interface the address is associated with.
              ifa_flags is a flag word of IFA_F_SECONDARY for secondary
              address (old alias interface), IFA_F_PERMANENT for a permanent
              address set by the user and other undocumented flags.

                                       Attributes
              rta_type        value type             description
              ─────────────────────────────────────────────────────────────
              IFA_UNSPEC      -                      unspecified.
              IFA_ADDRESS     raw protocol address   interface address
              IFA_LOCAL       raw protocol address   local address
              IFA_LABEL       asciiz string          name of the interface
              IFA_BROADCAST   raw protocol address   broadcast address.
              IFA_ANYCAST     raw protocol address   anycast address
              IFA_CACHEINFO   struct ifa_cacheinfo   Address information.

       RTM_NEWROUTE, RTM_DELROUTE, RTM_GETROUTE
              Create, remove or receive information about a network route.
              These messages contain an rtmsg structure with an optional
              sequence of rtattr structures following.  For RTM_GETROUTE,
              setting rtm_dst_len and rtm_src_len to 0 means you get all
              entries for the specified routing table.  For the other
              fields, except rtm_table and rtm_protocol, 0 is the wildcard.

              struct rtmsg {
                  unsigned char rtm_family;   /* Address family of route */
                  unsigned char rtm_dst_len;  /* Length of destination */
                  unsigned char rtm_src_len;  /* Length of source */
                  unsigned char rtm_tos;      /* TOS filter */

                  unsigned char rtm_table;    /* Routing table ID */
                  unsigned char rtm_protocol; /* Routing protocol; see below */
                  unsigned char rtm_scope;    /* See below */
                  unsigned char rtm_type;     /* See below */

                  unsigned int  rtm_flags;
              };

              rtm_type          Route type
              ───────────────────────────────────────────────────────────
              RTN_UNSPEC        unknown route
              RTN_UNICAST       a gateway or direct route
              RTN_LOCAL         a local interface route
              RTN_BROADCAST     a local broadcast route (sent as a
                                broadcast)
              RTN_ANYCAST       a local broadcast route (sent as a uni‐
                                cast)
              RTN_MULTICAST     a multicast route
              RTN_BLACKHOLE     a packet dropping route
              RTN_UNREACHABLE   an unreachable destination
              RTN_PROHIBIT      a packet rejection route
              RTN_THROW         continue routing lookup in another table
              RTN_NAT           a network address translation rule
              RTN_XRESOLVE      refer to an external resolver (not
                                implemented)

              rtm_protocol      Route origin.
              ────────────────────────────────────────────
              RTPROT_UNSPEC     unknown
              RTPROT_REDIRECT   by an ICMP redirect (cur‐
                                rently unused)
              RTPROT_KERNEL     by the kernel
              RTPROT_BOOT       during boot
              RTPROT_STATIC     by the administrator

              Values larger than RTPROT_STATIC are not interpreted by the
              kernel, they are just for user information.  They may be used
              to tag the source of a routing information or to distinguish
              between multiple routing daemons.  See <linux/rtnetlink.h> for
              the routing daemon identifiers which are already assigned.

              rtm_scope is the distance to the destination:

              RT_SCOPE_UNIVERSE   global route
              RT_SCOPE_SITE       interior route in the
                                  local autonomous system
              RT_SCOPE_LINK       route on this link
              RT_SCOPE_HOST       route on the local host
              RT_SCOPE_NOWHERE    destination doesn't exist

              The values between RT_SCOPE_UNIVERSE and RT_SCOPE_SITE are
              available to the user.

              The rtm_flags have the following meanings:

              RTM_F_NOTIFY     if the route changes, notify the user via
                               rtnetlink
              RTM_F_CLONED     route is cloned from another route
              RTM_F_EQUALIZE   a multipath equalizer (not yet implemented)

              rtm_table specifies the routing table

              RT_TABLE_UNSPEC    an unspecified routing table
              RT_TABLE_DEFAULT   the default table
              RT_TABLE_MAIN      the main table
              RT_TABLE_LOCAL     the local table

              The user may assign arbitrary values between RT_TABLE_UNSPEC
              and RT_TABLE_DEFAULT.

                                       Attributes

              rta_type        value type         description
              ──────────────────────────────────────────────────────────────

              RTA_UNSPEC      -                  ignored.

              RTA_DST         protocol address   Route destination address.

              RTA_SRC         protocol address   Route source address.

              RTA_IIF         int                Input interface index.

              RTA_OIF         int                Output interface index.

              RTA_GATEWAY     protocol address   The gateway of the route

              RTA_PRIORITY    int                Priority of route.

              RTA_PREFSRC

              RTA_METRICS     int                Route metric

              RTA_MULTIPATH

              RTA_PROTOINFO

              RTA_FLOW

              RTA_CACHEINFO

              Fill these values in!

       RTM_NEWNEIGH, RTM_DELNEIGH, RTM_GETNEIGH
              Add, remove or receive information about a neighbor table
              entry (e.g., an ARP entry).  The message contains an ndmsg
              structure.

              struct ndmsg {
                  unsigned char ndm_family;
                  int           ndm_ifindex;  /* Interface index */
                  __u16         ndm_state;    /* State */
                  __u8          ndm_flags;    /* Flags */
                  __u8          ndm_type;
              };

              struct nda_cacheinfo {
                  __u32         ndm_confirmed;
                  __u32         ndm_used;
                  __u32         ndm_updated;
                  __u32         ndm_refcnt;
              };

              ndm_state is a bit mask of the following states:

              NUD_INCOMPLETE   a currently resolving cache entry
              NUD_REACHABLE    a confirmed working cache entry
              NUD_STALE        an expired cache entry

              NUD_DELAY        an entry waiting for a timer
              NUD_PROBE        a cache entry that is currently reprobed
              NUD_FAILED       an invalid cache entry

              NUD_NOARP        a device with no destination cache
              NUD_PERMANENT    a static entry

              Valid ndm_flags are:

              NTF_PROXY    a proxy arp entry
              NTF_ROUTER   an IPv6 router

              The rtattr struct has the following meanings for the rta_type
              field:

              NDA_UNSPEC      unknown type
              NDA_DST         a neighbor cache n/w layer destination address
              NDA_LLADDR      a neighbor cache link layer address

              NDA_CACHEINFO   cache statistics.

              If the rta_type field is NDA_CACHEINFO, then a struct
              nda_cacheinfo header follows

       RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE
              Add, delete or retrieve a routing rule.  Carries a struct
              rtmsg

       RTM_NEWQDISC, RTM_DELQDISC, RTM_GETQDISC
              Add, remove or get a queueing discipline.  The message con‐
              tains a struct tcmsg and may be followed by a series of
              attributes.

              struct tcmsg {
                  unsigned char    tcm_family;
                  int              tcm_ifindex;   /* interface index */
                  __u32            tcm_handle;    /* Qdisc handle */
                  __u32            tcm_parent;    /* Parent qdisc */
                  __u32            tcm_info;
              };

                                        Attributes

              rta_type     value type           Description
              ────────────────────────────────────────────────────────────────
              TCA_UNSPEC   -                    unspecified

              TCA_KIND     asciiz string        Name of queueing discipline
              TCA_OPTIONS  byte sequence        Qdisc-specific options follow
              TCA_STATS    struct tc_stats      Qdisc statistics.

              TCA_XSTATS   qdisc-specific       Module-specific statistics.
              TCA_RATE     struct tc_estimator  Rate limit.

              In addition, various other qdisc-module-specific attributes
              are allowed.  For more information see the appropriate include
              files.

       RTM_NEWTCLASS, RTM_DELTCLASS, RTM_GETTCLASS
              Add, remove or get a traffic class.  These messages contain a
              struct tcmsg as described above.

       RTM_NEWTFILTER, RTM_DELTFILTER, RTM_GETTFILTER
              Add, remove or receive information about a traffic filter.
              These messages contain a struct tcmsg as described above.

VERSIONS         top

       rtnetlink is a new feature of Linux 2.2.

BUGS         top

       This manual page is incomplete.
반응형

'흐어엉' 카테고리의 다른 글

친구야 너도 들어가 있어! 알았어...  (0) 2018.10.19
너까지 추가  (0) 2018.10.16
하두 맨날 찾와봐서 블로그에 박는다 (2)  (0) 2018.10.16