📄 5.t
字号:
corresponding to SOCK_DGRAM..NH 2Broadcasting and determining network configuration.PPBy using a datagram socket, it is possible to send broadcastpackets on many networks supported by the system.The network itself must support broadcast; the systemprovides no simulation of broadcast in software.Broadcast messages can place a high load on a network since they forceevery host on the network to service them. Consequently,the ability to send broadcast packets has been limitedto sockets which are explicitly marked as allowing broadcasting.Broadcast is typically used for one of two reasons:it is desired to find a resource on a local network without priorknowledge of its address,or important functions such as routing require that informationbe sent to all accessible neighbors..PPMulticasting is an alternative to broadcasting.Setting up IP multicast sockets is described in the next section..PPTo send a broadcast message, a datagram socket should be created:.DSs = socket(AF_INET, SOCK_DGRAM, 0);.DEor.DSs = socket(AF_NS, SOCK_DGRAM, 0);.DEThe socket is marked as allowing broadcasting,.DSint on = 1;setsockopt(s, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on));.DEand at least a port number should be bound to the socket:.DSsin.sin_family = AF_INET;sin.sin_addr.s_addr = htonl(INADDR_ANY);sin.sin_port = htons(MYPORT);bind(s, (struct sockaddr *) &sin, sizeof (sin));.DEor, for the NS domain,.DSsns.sns_family = AF_NS;netnum = htonl(net);sns.sns_addr.x_net = *(union ns_net *) &netnum; /* insert net number */sns.sns_addr.x_port = htons(MYPORT);bind(s, (struct sockaddr *) &sns, sizeof (sns));.DEThe destination address of the message to be broadcastdepends on the network(s) on which the message is to be broadcast.The Internet domain supports a shorthand notation for broadcaston the local network, the address INADDR_BROADCAST (defined in<\fInetinet/in.h\fP>.To determine the list of addresses for all reachable neighborsrequires knowledge of the networks to which the host is connected.Since this information shouldbe obtained in a host-independent fashion and may be impossibleto derive, 4.4BSD provides a method ofretrieving this information from the system data structures.The SIOCGIFCONF \fIioctl\fP call returns the interfaceconfiguration of a host in the form of asingle \fIifconf\fP structure; this structure containsa ``data area'' which is made up of an array ofof \fIifreq\fP structures, one for each network interfaceto which the host is connected.These structures are defined in\fI<net/if.h>\fP as follows:.DS.if t .ta .5i 1.0i 1.5i 3.5i.if n .ta .7i 1.4i 2.1i 3.4istruct ifconf { int ifc_len; /* size of associated buffer */ union { caddr_t ifcu_buf; struct ifreq *ifcu_req; } ifc_ifcu;};#define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */#define ifc_req ifc_ifcu.ifcu_req /* array of structures returned */#define IFNAMSIZ 16struct ifreq { char ifr_name[IFNAMSIZ]; /* if name, e.g. "en0" */ union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; short ifru_flags; caddr_t ifru_data; } ifr_ifru;};.if t .ta \w' #define'u +\w' ifr_broadaddr'u +\w' ifr_ifru.ifru_broadaddr'u#define ifr_addr ifr_ifru.ifru_addr /* address */#define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-to-p link */#define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */#define ifr_flags ifr_ifru.ifru_flags /* flags */#define ifr_data ifr_ifru.ifru_data /* for use by interface */.DEThe actual call which obtains theinterface configuration is.DSstruct ifconf ifc;char buf[BUFSIZ];ifc.ifc_len = sizeof (buf);ifc.ifc_buf = buf;if (ioctl(s, SIOCGIFCONF, (char *) &ifc) < 0) { ...}.DEAfter this call \fIbuf\fP will contain one \fIifreq\fP structure foreach network to which the host is connected, and\fIifc.ifc_len\fP will have been modified to reflect the numberof bytes used by the \fIifreq\fP structures..PPFor each structurethere exists a set of ``interface flags'' which tellwhether the network corresponding to that interface isup or down, point to point or broadcast, etc. TheSIOCGIFFLAGS \fIioctl\fP retrieves theseflags for an interface specified by an \fIifreq\fPstructure as follows:.DSstruct ifreq *ifr;ifr = ifc.ifc_req;for (n = ifc.ifc_len / sizeof (struct ifreq); --n >= 0; ifr++) { /* * We must be careful that we don't use an interface * devoted to an address family other than those intended; * if we were interested in NS interfaces, the * AF_INET would be AF_NS. */ if (ifr->ifr_addr.sa_family != AF_INET) continue; if (ioctl(s, SIOCGIFFLAGS, (char *) ifr) < 0) { ... } /* * Skip boring cases. */ if ((ifr->ifr_flags & IFF_UP) == 0 || (ifr->ifr_flags & IFF_LOOPBACK) || (ifr->ifr_flags & (IFF_BROADCAST | IFF_POINTTOPOINT)) == 0) continue;.DE.PPOnce the flags have been obtained, the broadcast address must be obtained. In the case of broadcast networks this isdone via the SIOCGIFBRDADDR \fIioctl\fP, while for point-to-point networksthe address of the destination host is obtained with SIOCGIFDSTADDR..DSstruct sockaddr dst;if (ifr->ifr_flags & IFF_POINTTOPOINT) { if (ioctl(s, SIOCGIFDSTADDR, (char *) ifr) < 0) { ... } bcopy((char *) ifr->ifr_dstaddr, (char *) &dst, sizeof (ifr->ifr_dstaddr));} else if (ifr->ifr_flags & IFF_BROADCAST) { if (ioctl(s, SIOCGIFBRDADDR, (char *) ifr) < 0) { ... } bcopy((char *) ifr->ifr_broadaddr, (char *) &dst, sizeof (ifr->ifr_broadaddr));}.DE.PPAfter the appropriate \fIioctl\fP's have obtained the broadcastor destination address (now in \fIdst\fP), the \fIsendto\fP call may beused:.DS sendto(s, buf, buflen, 0, (struct sockaddr *)&dst, sizeof (dst));}.DEIn the above loop one \fIsendto\fP occurs for everyinterface to which the host is connected that supports the notion ofbroadcast or point-to-point addressing.If a process only wished to send broadcastmessages on a given network, code similar to that outlined abovewould be used, but the loop would need to find thecorrect destination address..PPReceived broadcast messages contain the senders addressand port, as datagram sockets are bound beforea message is allowed to go out..NH 2IP Multicasting.PPIP multicasting is the transmission of an IP datagram to a "hostgroup", a set of zero or more hosts identified by a single IPdestination address. A multicast datagram is delivered to allmembers of its destination host group with the same "best-efforts"reliability as regular unicast IP datagrams, i.e., the datagram isnot guaranteed to arrive intact at all members of the destinationgroup or in the same order relative to other datagrams..PPThe membership of a host group is dynamic; that is, hosts may joinand leave groups at any time. There is no restriction on thelocation or number of members in a host group. A host may be amember of more than one group at a time. A host need not be a memberof a group to send datagrams to it..PPA host group may be permanent or transient. A permanent group has awell-known, administratively assigned IP address. It is the address,not the membership of the group, that is permanent; at any time apermanent group may have any number of members, even zero. Those IPmulticast addresses that are not reserved for permanent groups areavailable for dynamic assignment to transient groups which exist onlyas long as they have members..PPIn general, a host cannot assume that datagrams sent to any hostgroup address will reach only the intended hosts, or that datagramsreceived as a member of a transient host group are intended for therecipient. Misdelivery must be detected at a level above IP, usinghigher-level identifiers or authentication tokens. Informationtransmitted to a host group address should be encrypted or governedby administrative routing controls if the sender is concerned aboutunwanted listeners..PPIP multicasting is currently supported only on AF_INET sockets of typeSOCK_DGRAM and SOCK_RAW, and only on subnetworks for which the interfacedriver has been modified to support multicasting..PPThe next subsections describe how to send and receive multicast datagrams..NH 3 Sending IP Multicast Datagrams.PPTo send a multicast datagram, specify an IP multicast address in the range224.0.0.0 to 239.255.255.255 as the destination addressin a.IR sendto (2)call..PPThe definitions required for the multicast-related socket options arefound in \fI<netinet/in.h>\fP.All IP addresses are passed in network byte-order..PPBy default, IP multicast datagrams are sent with a time-to-live (TTL) of 1,which prevents them from being forwarded beyond a single subnetwork. A newsocket option allows the TTL for subsequent multicast datagrams to be set toany value from 0 to 255, in order to control the scope of the multicasts:.DSu_char ttl;setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));.DEMulticast datagrams with a TTL of 0 will not be transmitted on any subnet,but may be delivered locally if the sending host belongs to the destinationgroup and if multicast loopback has not been disabled on the sending socket(see below). Multicast datagrams with TTL greater than one may be deliveredto more than one subnet if there are one or more multicast routers attachedto the first-hop subnet. To provide meaningful scope control, the multicastrouters support the notion of TTL "thresholds", which prevent datagrams withless than a certain TTL from traversing certain subnets. The thresholdsenforce the following convention:.TScenter;l | ll | n._Scope Initial TTL=restricted to the same host 0restricted to the same subnet 1restricted to the same site 32restricted to the same region 64restricted to the same continent 128unrestricted 255_.TE"Sites" and "regions" are not strictly defined, and sites may be furthersubdivided into smaller administrative units, as a local matter..PPAn application may choose an initial TTL other than the ones listed above.For example, an application might perform an "expanding-ring search" for anetwork resource by sending a multicast query, first with a TTL of 0, andthen with larger and larger TTLs, until a reply is received, perhaps usingthe TTL sequence 0, 1, 2, 4, 8, 16, 32..PPThe multicast router.IR mrouted (8),refuses to forward anymulticast datagram with a destination address between 224.0.0.0 and224.0.0.255, inclusive, regardless of its TTL. This range of addresses isreserved for the use of routing protocols and other low-level topologydiscovery or maintenance protocols, such as gateway discovery and groupmembership reporting..PPThe address 224.0.0.0 isguaranteed not to be assigned to any group, and 224.0.0.1 is assignedto the permanent group of all IP hosts (including gateways). This isused to address all multicast hosts on the directly connectednetwork. There is no multicast address (or any other IP address) forall hosts on the total Internet. The addresses of other well-known,permanent groups are published in the "Assigned Numbers" RFC,which is available from the InterNIC..PPEach multicast transmission is sent from a single network interface, even ifthe host has more than one multicast-capable interface. (If the host isalso serving as a multicast router,a multicast may be \fIforwarded\fP to interfacesother than originating interface, provided that the TTL is greater than 1.)The default interface to be used for multicasting is the primary networkinterface on the system.A socket optionis available to override the default for subsequent transmissions from agiven socket:.DSstruct in_addr addr;setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));.DEwhere "addr" is the local IP address of the desired outgoing interface.An address of INADDR_ANY may be used to revert to the default interface.The local IP address of an interface can be obtained via the SIOCGIFCONFioctl. To determine if an interface supports multicasting, fetch theinterface flags via the SIOCGIFFLAGS ioctl and see if the IFF_MULTICASTflag is set. (Normal applications should not need to use this option; itis intended primarily for multicast routers and other system servicesspecifically concerned with internet topology.)The SIOCGIFCONF and SIOCGIFFLAGS ioctls are described in the previous section..PPIf a multicast datagram is sent to a group to which the sending host itselfbelongs (on the outgoing interface), a copy of the datagram is, by default,looped back by the IP layer for local delivery. Another socket option givesthe sender explicit control over whether or not subsequent datagrams arelooped back:.DSu_char loop;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -