Friday, December 27, 2019

Prepositions in English Grammar

In English grammar, a preposition is a word that shows the relationship between a noun or pronoun and other words in a sentence. Prepositions are words like in and out, above and below, and to and from,  and theyre words we use all the time. How useful are prepositions? Just look at how many prepositions are italicized in this simple sentence from E.B. Whites Charlottes Web: For  the first few days  of  his life, Wilbur was allowed to live  in  a box  near  the stove  in  the kitchen. Prepositions in English Grammar Prepositions are one of the basic  parts of speech  and are among the words that we use most when composing sentences. They are also a member of a closed word class, meaning  that it is very rare for a new preposition to enter the language. There are only about 100 of them in English. Prepositions often refer to location  (under  the table), direction (to  the south), or time (past  midnight). They can also be used to convey other relationships: agency (by), comparison (like, as . . . as), possession (of), purpose (for), or source (from, out of). Simple Prepositions Many prepositions are made up of only one word and are called  simple prepositions. These include short and very common words like  as, at, by, for, and of.  You also use prepositions such as about, between, into, like, onto, since, than, through, with, within, and without to show a relationship between words. There are many occasions where you might confuse prepositions. For example, sometimes it is difficult to know when you should use  in, into, on, or at.  This is because their meanings are very similar, so you have to look at the context of the sentence. Many prepositions have an opposite as well. For instance, you can use  before or after, inside or outside, off or on, over or under, and  up or down.   Quite a few prepositions express the relationship of things in space. Examples of these include aboard, across, amid, among, around, atop, behind, beneath, beside, beyond, near, over, round,  and upon. Prepositions can also refer to time. Among the most common are  after, before,  during, till,  and  until. Other prepositions have unique uses or can be used in multiple ways. Some of these include  about, against, along, despite, regarding, throughout, toward,  and  unlike. Complex Prepositions In addition  to  the simple prepositions, several word groups can perform the same grammatical function. These are called  complex prepositions. They are two- or three-word units that combine one or two simple prepositions with another word. Within this category, you have phrases like  in addition to  and such as.  Whenever you say  thanks to or in between, you are also using a complex preposition. Identifying Prepositional Phrases Prepositions are not in the habit of standing alone. A word group with a preposition at the head followed by an  object  (or  complement) is called a  prepositional phrase. The object of a preposition is typically a  noun  or  pronoun:  Gus put the horse  before the cart. Prepositional phrases add meaning to the nouns and verbs in sentences. They usually tell us  where, when,  or  how and the words of a prepositional phrase can often be rearranged. A prepositional phrase may do the work of an  adjective  and modify a noun:  The student  in the back row  began to snore loudly. It may also function as an  adverb  and modify a verb:  Buster fell asleep  during class. Learning to identify prepositional phrases is often a matter of practice. After some time you will come to realize how frequently we rely on them. Ending a Sentence With a Preposition You may have a heard the rule that you should never  end a sentence with a preposition. This is one of those rules that you dont have to put up with. It is based on the etymology of preposition, from the Greek for put in front, as well as a false analogy to Latin. As long ago as 1926, Henry Fowler dismissed the rule about preposition  stranding as a cherished superstition ignored by major writers from Shakespeare to Thackeray. In fact, in A Dictionary of Modern English Usage he said, the remarkable freedom enjoyed by English in putting its  prepositions  late and omitting its relatives is an important element in the flexibility of the language. Essentially, you can ignore this rule, and you can cite Fowler to anyone who tells you otherwise. Go ahead and end your sentence with a preposition if you want to. Prepositions Functioning as Another Part of Speech Just because you see one of the prepositions weve mentioned used, does not mean that they are being used as a preposition. It depends on the circumstances, and this is one of those tricky parts of the English language, so dont let these fool you. Certain prepositions (after, as, before, since, until) serve as  subordinating conjunctions  when theyre followed by a  clause: You better get out of town  before  sundown. (Before  is used as a preposition.)Many people run out of ideas long  before  they run out of words. (Before  is used as a conjunction.) Some prepositions (including  about, across, around, before, down, in, on, out,  and  up) also moonlight as  adverbs. These are sometimes called  prepositional adverbs  or  adverbial  particles. Beth walked  up  the driveway. (The preposition up is followed by the object.)Beth looked  up. (The prepositional adverb up  is modifying the verb looked.) Deverbal Prepositions Transitive prepositions that take the same form as -ing participles or -ed participles are called deverbal prepositions. It is a rather short list, but it is important to understand that these are also prepositions. according (to)allowing (for)barringconcerningcountingexceptingexcludingfailingfollowinggivengonegrantedincludingowing (to)pertaining (to)regardingrespectingsavingtouchingwanting Source: Fowler H.  A Dictionary of Modern English Usage. 2nd ed. New York, NY: Oxford University Press; 1965.

Thursday, December 19, 2019

The Problem Of Climate Change - 1075 Words

There are millions of planets that has the possibility to sustain life on a planet, but not a single one we know of like earth. fermi paradox says there are things called life barriers and there are certain barriers that have â€Å"filters†. filters only let the smartest lifeforms through them if they are real. They state electricity and earth or ourselves evolution are huge barriers that was destroyed. If an asteroid hit the earth or nuclear warfare happens it is a huge reason we have lost. According to the fermi paradox we either pass this wall (barrier) or not. I have my conclusion of why we will fail, it is because humans are selfish, hard headed, fool mined incompetent beings. Climate change is the barrier that we don t really have any research on. El ninos and la ninas are the cause. To know El Nià ±o, you need to know the intercoarse between the ocean and the atmosphere. Warm ocean surface water currents heats and adds moistness to the air above it, forming a low press ure system. Cool surface water cools the air above it, forming a high pressure system . In a Low, the warm, moist air produces tropical thunderstorms. In a High, cool, parched air sinks back to the surface and there is no precipitation. Together, the High and Low create a circulation pattern in which surface winds blow toward the Low and higher-level winds rushes toward the High. An El nino come from the spanish word little boy. It was found by fisherman by the coast of south america in the 1600sShow MoreRelatedThe Problem Of Climate Change1438 Words   |  6 Pagessplash in the water. However, there is one problem, an action such as driving to the beach front will almost certainly contribute to the destructive effects of climate change. Due to this claim, is it then morally obligatory to not go on this Sunday morning drive in an effort to prevent greenhouse gas emissions? This is the question I would like to address. Each day individuals commit actions of miniscule value that arguably contribute to climate change. Driving a car on a Sunday morning is justRead MoreThe Problem Of Climate Change1745 Words   |  7 Pagesaltered by humans, including the climate. Climate change is becoming one of the fastest growing problems that the world is facing. Once one thing changes, it causes a ripple effect creating complications for Earth and everything that is part of Earth. If this problem is not fixed soon, the Earth as we know it will be forever changed. One of the biggest problems about the topic of climate change is that people do not understand the meaning of climate change or what problems that it can cause if it is untreatedRead MoreThe Problem Of Climate Change904 Words   |  4 PagesClimate Change Have you ever wonder that what is our true enemy of the earth? Would what people had done will be alright? If we look at the world crisis now a day, people might know that everywhere around the world the number one problem probably be climate change. In the past, one thousand the world we live never change so much. But what happened is in 5 years we have seen something that is quite difficult to be seen such as earthquake, flood, and hurricane. There is the anger of nature that isRead MoreThe Problem Of Climate Change1188 Words   |  5 Pagesis involved with the climate change in California? Humans, corporations, electricity generators, petroleum refineries facilities, oil and gas production, hydrogen plants, and cogeneration. What part of the country is exactly doing the most damage? Long Beach - Los Angeles, CA. How many people are affected, according to official records? People who are residences in California, are the one who are most affected. Mostly the general people, who i s in the radius of climate change. For example SacramentoRead MoreClimate Change Is A Serious Problem1123 Words   |  5 PagesClimate Change is a Serious Problem to the Planet â€Å"Climate change is happening, humans are causing it, and I think it is perhaps the most serious environmental issue facing us.† This quote from Bill Nye illustrates the serious nature of climate change. Climate change is the most serious issue that is plaguing the world. Global temperatures have been increasing in recent years and it is clear that our climate is changing. Climate change is the change of temperature and weather in our environmentRead MoreClimate Change Is A Serious Problem1028 Words   |  5 PagesHumans will destroy the earth if no one acts. Climate change is a serious problem that has been around for decades. The 21st century is special because of the technology and information available. Yet, people continue to ignore the overwhelming destruction happening to nature. Through many years, masses have begun to take responsibility and restore the planet. In time, the earth might be what it once was. Climate change began in the 1820s with Joseph Fourier and in the 1860s with John Tyndall. FourierRead MoreClimate Change Is Real And A Problem Essay1229 Words   |  5 PagesThe issue is simple and rather obvious; climate change is real and a problem. With a changing climate comes rising sea levels, hotter days, and stronger and wilder storms, and long painful droughts. What most people can’t seem to agree on is whether or not human activity is playing some role in it. From media outlets to internet forums, the debate is being fought on all fronts. Most of these arguments, however, are just personal opinions and poorly-made observations from the comfort of a gas-guzzlingRead MoreProblems Associated With Climate Change1053 Words   |  5 Pages1. What is this report about? It considers threats and impacts associated with climate change could be reduced and handled through mitigation and adaptation. The report evaluates resilience, choices, opportunities, constraints, needs, limits, as well as other features connected with adaptation. Climate change requires shifting probabilities of impacts that are varied with complicated interactions. A focus on danger, which will be not old in this report, complements other aspects of the report andRead MoreClimate Change Is An Ongoing Problem1569 Words   |  7 PagesClimate change is an ongoing problem in our world. There are many health effects, shortage of resources due to energy use, and perhaps more importantly, the detrimental and in some cases irreversible environmental impacts. The climate does change due to natural forces, however; human impacts are the cause of such dramatic change. â€Å"Unless greenhouse gas emissions are severely reduced, climate change could cause a quarter of land animals, birdlife and plants to become extinct† (Weather InformationRead MoreClimate Change Is A Global Problem Essay1336 Words   |  6 PagesAnthropogenic climate change is often considered to be greatest threat currently posed on the world. Climate change fits into the public goods framework in terms of both mitigation and adaptation policy (Boyer 2013). Greenhouse gas (GHG) emissions produced by human activity are heavily impacting the climate, and thus creating externalities that are impacting the globe, such as rising global temperatures, increasing extreme weather incidents, and changing weather patterns. These externalities are

Wednesday, December 11, 2019

Use of Supplant Growth and Technology †MyAssignmenthelp.com

Question: Discuss about the Use of Supplant Growth and Technology. Answer: Value Proposition for Growers Growers who participate in this Supplant Growth based Irrigation initiative shall have experienced one area of the farm responding differently from another until now. With the use of Supplant technology, they shall be able to reduce these variations. With the application of the equipment on the plant, all that growers need is a smart phone. Sensors monitor the crop and their environment. Using this technology reduce the need to be on the farm all the time and the number of pivot rounds. It increases the yields quantity as well as quality and make all parts of the farm equally usable(Supplant 2017). Value Proposition for Vendors Irrigation suppliers are motivated to find new and innovative technologies to benefit their consumers by providing them cost effective means of production and thus attract more farmers and growers to buy from them. The manufacturers focus on increased revenue by producing more units and creating additional revenue flow. Application developers and data warehouse companies are also keen to invest in such software based irrigation systems to help farmers manage farm operations. Irrigation consultants on the other hand look forward to expand their client base as they become trusted advisors of such system for farmers who are beginning to adopt the technology and need constant support(Supplant 2017). Value Proposition for Government The Growth based Irrigation system shall benefit the government in helping them regulate their policies and regulations related to irrigation. Also the government shall collaborate with the technology providers and provide the technology to small farmers at reasonable rate. This shall enable them gain control over water deficits in the areas and increase the farm productivity. Thus, curbing farmer suicides, losses faced by them, improve the quality of their lives and steady income (Levidow et al. 2014). Value Proposition for Employees The employees of the company shall get an opportunity to work with new and innovative technology. This shall enable them grow their technological andmanagement skills. The company believes to promote learning and overall development of its employees at all the level. Global recruitment and horizontal employee shifts shall comprehend them with working of different economies. The local employees shall also be placed at different operational locations to understand how the technology is promoted in different locations. The employees also enjoy benefits at the corporate office and special deals at variety of stores and outlets across the world. (Goldtec Control Systems 2017). Value Proposition for Community and Society The firm shall recognize local schools and colleges to educate the locals about the healthier and cost efficient irrigation system. This shall contribute to the literacy of the farmers and their families for better future. The real time data storing shall enable to keep the environment in check and take control measures and make environment healthier by saving on energy and water requirement. Healthier yield shall also enable the better health of the society. Recruitment at ground level of all the farming locations shall enable fostering the social justice and employability of all the sections of the society (Mutambara, Mutambara and Darkoh 2014). References Goldtec Control Systems, 2017. SupPlant | Goldtec. [online] Goldtecsystems.com.au. Available at: https://goldtecsystems.com.au/product/supplant/ [Accessed 7 Oct. 2017]. Levidow, L., Zaccaria, D., Maia, R., Vivas, E., Todorovic, M. and Scardigno, A., 2014. Improving water-efficient irrigation: Prospects and difficulties of innovative practices. Agricultural Water Management, 146(1), pp.84-94. Mutambara, S., Mutambara, J. and Darkoh, M., 2014. Towards sustainable stakeholder engagement in smallholder irrigation schemes in Zimbabwe. African Journal of Agricultural Research, 9(50), pp.3588-3599. Supplant, 2017. Smart farm enablers. [online] https://supplant.me/. Available at: https://supplant.me/ [Accessed 7 Oct. 2017].

Tuesday, December 3, 2019

Network Programming with Sockets Essay Example

Network Programming with Sockets Essay Socket programming got you down? Is this stuff just a little too difficult to figure out from the man pages? You want to do cool Internet programming, but you dont have time to wade through a gob of structs trying to figure out if you have to call bind() before you connect(), etc. , etc. Well, guess what! Ive already done this nasty business, and Im dying to share the information with everyone! Youve come to the right place.This document should give the average competent C programmer the edge s/he needs to get a grip on this networking noise. Audience This document has been written as a tutorial, not a reference. It is probably at its best when read by individuals who are just starting out with socket programming and are looking for a foothold. It is certainly not the complete guide to sockets programming, by any means. Hopefully, though, itll be just enough for those man pages to start making sense 🙂 Platform and Compiler Most of the code contained within this document was compiled on a Linux PC using Gnus gcc compiler.It was also found to compile on HPUX using gcc. Note that every code snippet was not individually tested. Contents: What is a socket? Two Types of Internet Sockets Low level Nonsense and Network Theory structsKnow these, or aliens will destroy the planet! Convert the Natives! IP Addresses and How to Deal With Them socket()Get the File Descriptor! bind()What port am I on? connect()Hey, you! listen()Will somebody please call me? 1 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html accept()Thank you for calling port 3490. end() and recv()Talk to me, baby! sendto() and recvfrom()Talk to me, DGRAM-style close() and shutdown()Get outta my face! getpeername()Who are you? gethostname()Who am I? DNSYou say whitehouse. gov, I say 198. 137. 240. 100 Client-Server Background A Simple Stream Server A Simple Stream Client Datagram Sockets Blocking select()Synch ronous I/O Multiplexing. Cool! More references Disclaimer and Call for Help What is a socket? You hear talk of sockets all the time, and perhaps you are wondering just what they are exactly. Well, theyre this: a way to speak to other programs using standard Unix file descriptors.What? Okyou may have heard some Unix hacker state, Jeez, everything in Unix is a file! What that person may have been talking about is the fact that when Unix programs do any sort of I/O, they do it by reading or writing to a file descriptor. A file descriptor is simply an integer associated with an open file. But (and heres the catch), that file can be a network connection, a FIFO, a pipe, a terminal, a real on-the-disk file, or just about anything else. Everything in Unix is a file! So when you want to communicate with another program over the Internet youre gonna do it through a file descriptor, youd better believe it. Where do I get this file descriptor for network communication, Mr. Smarty-Pants? is p robably the last question on your mind right now, but Im going to answer it anyway: You make a call to the socket() system routine. It returns the socket descriptor, and you communicate through it using the specialized send() and recv() (man send, man recv) socket calls. But, hey! you might be exclaiming right about now. If its a file descriptor, why in the hell cant I just use the normal read() and write() calls to communicate through the socket? The short answer is, You can! The longer answer is, You can, but send() and recv() offer much greater control over your data transmission. What next? How about this: there are all kinds of sockets. There are DARPA Internet addresses (Internet Sockets), path names on a local node (Unix Sockets), CCITT X. 25 addresses (X. 25 Sockets that you can safely ignore), and probably many others depending on which Unix flavor you run. This document deals only with the first: Internet Sockets. Two Types of Internet Sockets 2 of 26 12. 03. 99 01:21 B eejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. tml Whats this? There are two types of Internet sockets? Yes. Well, no. Im lying. There are more, but I didnt want to scare you. Im only going to talk about two types here. Except for this sentence, where Im going to tell you that Raw Sockets are also very powerful and you should look them up. All right, already. What are the two types? One is Stream Sockets; the other is Datagram Sockets, which may hereafter be referred to as SOCK_STREAM and SOCK_DGRAM, respectively. Datagram sockets are sometimes called connectionless sockets (though they can be connect()d if you really want.See connect(), below. Stream sockets are reliable two-way connected communication streams. If you output two items into the socket in the order 1, 2, they will arrive in the order 1, 2 at the opposite end. They will also be error free. Any errors you do encounter are figments of your own deranged min d, and are not to be discussed here. What uses stream sockets? Well, you may have heard of the telnet application, yes? It uses stream sockets. All the characters you type need to arrive in the same order you type them, right? Also, WWW browsers use the HTTP protocol which uses stream sockets to get pages.Indeed, if you telnet to a WWW site on port 80, and type GET pagename, itll dump the HTML back at you! How do stream sockets achieve this high level of data transmission quality? They use a protocol called The Transmission Control Protocol, otherwise known as TCP (see RFC-793 for extremely detailed info on TCP. ) TCP makes sure your data arrives sequentially and error-free. You may have heard TCP before as the better half of TCP/IP where IP stands for Internet Protocol (see RFC-791. ) IP deals with Internet routing only. Cool. What about Datagram sockets? Why are they called connectionless?What is the deal, here, anyway? Why are they unreliable? Well, here are some facts: if you se nd a datagram, it may arrive. It may arrive out of order. If it arrives, the data within the packet will be error-free. Datagram sockets also use IP for routing, but they dont use TCP; they use the User Datagram Protocol, or UDP (see RFC-768. ) Why are they connectionless? Well, basically, its because you dont have to maintain an open connection as you do with stream sockets. You just build a packet, slap an IP header on it with destination information, and send it out. No connection needed.They are generally used for packet-by-packet transfers of information. Sample applications: tftp, bootp, etc. Enough! you may scream. How do these programs even work if datagrams might get lost?! Well, my human friend, each has its own protocol on top of UDP. For example, the tftp protocol says that for each packet that gets sent, the recipient has to send back a packet that says, I got it! (an ACK packet. ) If the sender of the original packet gets no reply in, say, five seconds, hell re-tran smit the packet until he finally gets an ACK. This acknowledgment procedure is very important when implementing SOCK_DGRAM applications.Low level Nonsense and Network Theory Since I just mentioned layering of protocols, its time to talk about how networks really work, and to show some examples of how SOCK_DGRAM packets are built. Practically, you can probably skip this section. Its good background, however. 3 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Hey, kids, its time to learn about Data Encapsulation! This is very very important. Its so important that you might just learn about it if you take the networks course here at Chico State ;-).Basically, it says this: a packet is born, the packet is wrapped (encapsulated) in a header (and maybe footer) by the first protocol (say, the TFTP protocol), then the whole thing (TFTP header included) is encapsulated again by the next protocol (say, UDP), then again by the next (IP), then again by the final protocol on the hardware (physical) layer (say, Ethernet). When another computer receives the packet, the hardware strips the Ethernet header, the kernel strips the IP and UDP headers, the TFTP program strips the TFTP header, and it finally has the data. Now I can finally talk about the infamous Layered Network Model.This Network Model describes a system of network functionality that has many advantages over other models. For instance, you can write sockets programs that are exactly the same without caring how the data is physically transmitted (serial, thin Ethernet, AUI, whatever) because programs on lower levels deal with it for you. The actual network hardware and topology is transparent to the socket programmer. Without any further ado, Ill present the layers of the full-blown model. Remember this for network class exams: Application Presentation Session Transport Network Data Link Physical The Physical Layer is the ha rdware (serial, Ethernet, etc. . The Application Layer is just about as far from the physical layer as you can imagineits the place where users interact with the network. Now, this model is so general you could probably use it as an automobile repair guide if you really wanted to. A layered model more consistent with Unix might be: Application Layer (telnet, ftp, etc. ) Host-to-Host Transport Layer (TCP, UDP) Internet Layer (IP and routing) Network Access Layer (was Network, Data Link, and Physical) At this point in time, you can probably see how these layers correspond to the encapsulation of the original data.See how much work there is in building a simple packet? Jeez! And you have to type in the packet headers yourself using cat! Just kidding. All you have to do for stream sockets is send() the data out. All you have to do for datagram sockets is encapsulate the packet in the method of your choosing and sendto() it out. The kernel builds the Transport Layer and Internet Layer on for you and the hardware does the Network Access Layer. Ah, modern technology. So ends our brief foray into network theory. Oh yes, I forgot to tell you everything I wanted to say about routing: nothing! Thats right, Im not going to talk about it at all.The router strips the packet to the IP header, consults its routing table, blah blah blah. Check out the IP RFC if you really really care. If you never learn about it, well, youll live. [Encapsulated Protocols Image] 4 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html structs Well, were finally here. Its time to talk about programming. In this section, Ill cover various data types used by the sockets interface, since some of them are a real bitch to figure out. First the easy one: a socket descriptor.A socket descriptor is the following type: int Just a regular int. Things get weird from here, so just read through and bear with me. Know this: there are two byte orderings: most significant byte (sometimes called an octet) first, or least significant byte first. The former is called Network Byte Order. Some machines store their numbers internally in Network Byte Order, some dont. When I say something has to be in NBO, you have to call a function (such as htons()) to change it from Host Byte Order. If I dont say NBO, then you must leave the value in Host Byte Order. My First Struct(TM)struct sockaddr.This structure holds socket address information for many types of sockets: struct sockaddr { unsigned short sa_family; /* address family, AF_xxx */ char sa_data[14]; /* 14 bytes of protocol address */ }; sa_family can be a variety of things, but itll be AF_INET for everything we do in this document. sa_data contains a destination address and port number for the socket. This is rather unwieldy. To deal with struct sockaddr, programmers created a parallel structure: struct sockaddr_in (in for Internet. ) struct sockaddr_in { shor t int sin_family; /* Address family */ unsigned short int sin_port; /* Port number */ truct in_addr sin_addr; /* Internet address */ unsigned char sin_zero[8]; /* Same size as struct sockaddr */ }; This structure makes it easy to reference elements of the socket address. Note that sin_zero (which is included to pad the structure to the length of a struct sockaddr) should be set to all zeros with the function bzero() or memset(). Also, and this is the important bit, a pointer to a struct sockaddr_in can be cast to a pointer to a struct sockaddr and vice-versa. So even though socket() wants a struct sockaddr *, you can still use a struct sockaddr_in and cast it at the last minute!Also, notice that sin_family corresponds to sa_family in a struct sockaddr and should be set to AF_INET. Finally, the sin_port and sin_addr must be in Network Byte Order! But, you object, how can the entire structure, struct in_addr sin_addr, be in Network Byte Order? This question requires careful examinati on of the structure struct in_addr, one of the worst unions alive: /* Internet address (a structure for historical reasons) */ 5 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html struct in_addr { nsigned long s_addr; }; Well, it used to be a union, but now those days seem to be gone. Good riddance. So if you have declared ina to be of type struct sockaddr_in, then ina. sin_addr. s_addr references the 4 byte IP address (in Network Byte Order). Note that even if your system still uses the God-awful union for struct in_addr, you can still reference the 4 byte IP address in exactly the same way as I did above (this due to #defines. ) Convert the Natives! Weve now been lead right into the next section. Theres been too much talk about this Network to Host Byte Order conversionnow is the time for action!All righty. There are two types that you can convert: short (two bytes) and long (four bytes). The se functions work for the unsigned variations as well. Say you want to convert a short from Host Byte Order to Network Byte Order. Start with h for host, follow it with to, then n for network, and s for short: h-to-n-s, or htons() (read: Host to Network Short). Its almost too easy You can use every combination if n, h, s, and l you want, not counting the really stupid ones. For example, there is NOT a stolh() (Short to Long Host) functionnot at this party, anyway.But there are: htons()Host to Network Short htonl()Host to Network Long ntohs()Network to Host Short ntohl()Network to Host Long Now, you may think youre wising up to this. You might think, What do I do if I have to change byte order on a char? Then you might think, Uh, never mind. You might also think that since your 68000 machine already uses network byte order, you dont have to call htonl() on your IP addresses. You would be right, BUT if you try to port to a machine that has reverse network byte order, your program wi ll fail. Be portable! This is a Unix world!Remember: put your bytes in Network Order before you put them on the network. A final point: why do sin_addr and sin_port need to be in Network Byte Order in a struct sockaddr_in, but sin_family does not? The answer: sin_addr and sin_port get encapsulated in the packet at the IP and UDP layers, respectively. Thus, they must be in Network Byte Order. However, the sin_family field is only used by the kernel to determine what type of address the structure contains, so it must be in Host Byte Order. Also, since sin_family does not get sent out on the network, it can be in Host Byte Order.IP Addresses and How to Deal With Them Fortunately for you, there are a bunch of functions that allow you to manipulate IP addresses. No need to figure them out by hand and stuff them in a long with the h_addr); bzero(;(their_addr. sin_zero), 8); /* zero the rest of the struct */ if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *);thei r_addr, sizeof(struct sockaddr))) == -1) { perror(sendto); exit(1); } printf(sent %d bytes to %s ,numbytes,inet_ntoa(their_addr. sin_addr)); close(sockfd); return 0; } And thats all there is to it!Run listener on some machine, then run talker on another. Watch them communicate! Fun G-rated excitement for the entire nuclear family! Except for one more tiny detail that Ive mentioned many times in the past: connected datagram sockets. I need to talk about this here, since were in the datagram section of the document. Lets say that talker calls connect() and specifies the listeners address. From that point on, talker may only sent to and receive from the address specified by connect(). For this reason, you dont have to use sendto() and recvfrom(); you can simply use send() and recv().Blocking Blocking. Youve heard about itnow what the hell is it? In a nutshell, block is techie jargon for sleep. You probably noticed that when you run listener, above, it just sits there until a packet arrives. What happened is that it called recvfrom(), there was no data, and so recvfrom() is said to block (that is, sleep there) until some data arrives. Lots of functions block. accept() blocks. All the recv*() functions block. The reason they can do this is because theyre allowed to. When you first create the socket descriptor with socket(), the kernel sets it to blocking.If you dont want a socket to be blocking, you have to make a call to fcntl(): #include #include . . sockfd = socket(AF_INET, SOCK_STREAM, 0); fcntl(sockfd, F_SETFL, O_NONBLOCK); . . By setting a socket to non-blocking, you can effectively poll the socket for information. If you try to read from a non-blocking socket and theres no data there, its not allowed to blockit will return -1 and errno will be set to EWOULDBLOCK. Generally speaking, however, this type of polling is a bad idea. If you put your program in a busy-wait looking for data on the socket, youll suck up CPU time like it was going out of style.A more elegant solution for checking to see if theres data waiting to be read comes in the following secti on on 21 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html select(). select()Synchronous I/O Multiplexing This function is somewhat strange, but its very useful. Take the following situation: you are a server and you want to listen for incoming connections as well as keep reading from the connections you already have. No problem, you say, just an accept() and a couple of recv()s. Not so fast, buster!What if youre blocking on an accept() call? How are you going to recv() data at the same time? Use non-blocking sockets! No way! You dont want to be a CPU hog. What, then? select() gives you the power to monitor several sockets at the same time. Itll tell you which ones are ready for reading, which are ready for writing, and which sockets have raised exceptions, if you really want to know that. Without any further ado, Ill offer the synopsis of select(): #include #include #include int select(int n umfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);The function monitors sets of file descriptors; in particular readfds, writefds, and exceptfds. If you want to see if you can read from standard input and some socket descriptor, sockfd, just add the file descriptors 0 and sockfd to the set readfds. The parameter numfds should be set to the values of the highest file descriptor plus one. In this example, it should be set to sockfd+1, since it is assuredly higher than standard input (0). When select() returns, readfds will be modified to reflect which of the file descriptors you selected is ready for reading. You can test them with the macro FD_ISSET(), below.Before progressing much further, Ill talk about how to manipulate these sets. Each set is of the type fd_set. The following macros operate on this type: FD_ZERO(fd_set *set) clears a file descriptor set FD_SET(int fd, fd_set *set) adds fd to the set FD_CLR(int fd, fd_set *set) removes fd fro m the set FD_ISSET(int fd, fd_set *set) tests to see if fd is in the set Finally, what is this weirded out struct timeval? Well, sometimes you dont want to wait forever for someone to send you some data. Maybe every 96 seconds you want to print Still Going to the terminal even though nothing has happened.This time structure allows you to specify a timeout period. If the time is exceeded and select() still hasnt found any ready file descriptors, itll return so you can continue processing. The struct timeval has the follow fields: struct timeval { int tv_sec; /* seconds */ int tv_usec; /* microseconds */ }; 22 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Just set tv_sec to the number of seconds to wait, and set tv_usec to the number of microseconds to wait. Yes, thats microseconds, not milliseconds.There are 1,000 microseconds in a millisecond, and 1,000 milliseconds in a second. Thus, th ere are 1,000,000 microseconds in a second. Why is it usec? The u is supposed to look like the Greek letter Mu that we use for micro. Also, when the function returns, timeout might be updated to show the time still remaining. This depends on what flavor of Unix youre running. Yay! We have a microsecond resolution timer! Well, dont count on it. Standard Unix timeslice is 100 milliseconds, so youll probably have to wait at least that long, no matter how small you set your struct timeval.Other things of interest: If you set the fields in your struct timeval to 0, select() will timeout immediately, effectively polling all the file descriptors in your sets. If you set the parameter timeout to NULL, it will never timeout, and will wait until the first file descriptor is ready. Finally, if you dont care about waiting for a certain set, you can just set it to NULL in the call to select(). The following code snippet waits 2. 5 seconds for something to appear on standard input: #include #incl ude #include #define STDIN 0 /* file descriptor for standard input */ main() { struct timeval tv; fd_set readfds; tv. v_sec = 2; tv. tv_usec = 500000; FD_ZERO(;readfds); FD_SET(STDIN, ;readfds); /* dont care about writefds and exceptfds: */ select(STDIN+1, ;readfds, NULL, NULL, ;tv); if (FD_ISSET(STDIN, ;readfds)) printf(A key was pressed! ); else printf(Timed out. ); } If youre on a line buffered terminal, the key you hit should be RETURN or it will time out anyway. Now, some of you might think this is a great way to wait for data on a datagram socketand you are right: it might be. Some Unices can use select in this manner, and some cant. You should see what your local man page says on the matter if you want to attempt it.One final note of interest about select(): if you have a socket that is listen()ing, you can check to see if there is a new connection by putting that sockets file descriptor in the readfds set. And that, my friends, is a quick overview of the almighty select() function. More References 23 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Youve come this far, and now youre screaming for more! Where else can you go to learn more about all this stuff? Try the following man pages, for starters: ocket() bind() connect() listen() accept() se nd() recv() sendto() recvfrom() close() shutdown() getpeername() getsockname() gethostbyname() gethostbyaddr() getprotobyname() fcntl() select() perror() Also, look up the following books: Internetworking with TCP/IP, volumes I-III by Douglas E. Comer and David L. Stevens. Published by Prentice Hall. Second edition ISBNs: 0-13-468505-9, 0-13-472242-6, 0-13-474222-2. There is a third edition of this set which covers IPv6 and IP over ATM. Using C on the UNIX System by David A. Curry. Published by OReilly ; Associates, Inc. ISBN 0-937175-23-4.TCP/IP Network Administration by Craig Hunt. Published by OReilly Associates, Inc. ISBN 0-937175-82-X. TCP/IP Illustrated, volumes 1-3 by W. Richard Stevens and Gary R. Wright. Published by Addison Wesley. ISBNs: 0-201-63346-9, 0-201-63354-X, 0-201-63495-3. Unix Network Programming by W. Richard Stevens. Published by Prentice Hall. ISBN 0-13-949876-1. On the web: BSD Sockets: A Quick And Dirty Primer (http://www. cs. umn. edu/~bentlema/unix/has o ther great Unix system programming info, too! ) Client-Server Computing (http://pandonia. canberra. edu. au/ClientServer/socket. html)Intro to TCP/IP (gopher) 24 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html (gopher://gopher-chem. ucdavis. edu/11/Index/Internet_aw/Intro_the_Internet/intro. to. ip/) Internet Protocol Frequently Asked Questions (France) (http://web. cnam. fr/Network/TCP-IP/) The Unix Socket FAQ (http://www. ibrado. com/sock-faq/) RFCsthe real dirt: RFC-768 The User Datagram Protocol (UDP) (ftp://nic. ddn. mil/rfc/rfc768. txt) RFC-791 The Internet Protocol (IP) (ftp://nic. ddn. mil/rfc/rfc791. txt)RFC-793 The Transmission Control Protocol (TCP) (ftp://nic. ddn. mil/rfc/rfc793. txt) RFC-854 The Telnet Protocol (ftp://nic. ddn. mil/rfc/rfc854. txt) RFC-951 The Bootstrap Protocol (BOOTP) (ftp://nic. ddn. mil/rfc/rfc951. txt) RFC-1350 The Trivial File Transfer Protocol (TFT P) (ftp://nic. ddn. mil/rfc/rfc1350. txt) Disclaimer and Call for Help Well, thats the lot of it. Hopefully at least some of the information contained within this document has been remotely accurate and I sincerely hope there arent any glaring errors. Well, sure, there always are. So, if there are, thats tough for you.Im sorry if any inaccuracies contained herein have caused you any grief, but you just cant hold me accountable. See, I dont stand behind a single word of this document, legally speaking. This is my warning to you: the whole thing could be a load of crap. But its probably not. After all, Ive spent many many hours messing with this stuff, and implemented several TCP/IP network utilities for Windows (including Telnet) as summer work. Im not the sockets god; Im just some guy. By the way, if anyone has any constructive (or destructive) criticism about this document, please send mail to [emailprotected] csuchico. du and Ill try to make an effort to set the record straight. I n case youre wondering why I did this, well, I did it for the money. Hah! No, really, I did it because a lot of people have asked me socket-related questions and when I tell them Ive been thinking about putting together a socket page, they say, cool! Besides, I feel that all this hard-earned knowledge is going to waste if I cant share it with others. WWW just happens to 25 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html be the perfect vehicle.I encourage others to provide similar information whenever possible. Enough of thisback to coding! 😉 Copyright  © 1995, 1996 by Brian Beej Hall. This guide may be reprinted in any medium provided that its content is not altered, it is presented in its entirety, and this copyright notice remains intact. Contact [emailprotected] csuchico. edu for more information. 26 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Da teien/Manualz/not ad ramming; Using Internet Sockets/net. htmlBeejs Guide to Network Programming Using Internet Sockets Version 1. 5. 4 (17-May-1998) [http://www. cst. csuchico. edu/~beej/guide/net] Intro Hey! Socket programming got you down? Is this stuff just a little too difficult to figure out from the man pages? You want to do cool Internet programming, but you dont have time to wade through a gob of structs trying to figure out if you have to call bind() before you connect(), etc. , etc. Well, guess what! Ive already done this nasty business, and Im dying to share the information with everyone! Youve come to the right place. This document should give the average competent C programmer the edge s/he needs to get a grip on this networking noise. AudienceThis document has been written as a tutorial, not a reference. It is probably at its best when read by individuals who are just starting out with socket programming and are looking for a foothold. It is certainly not the complete guide to sockets programming, by any means. Hopefully, though, itll be just enough for those man pages to start making sense 🙂 Platform and Compiler Most of the code contained within this document was compiled on a Linux PC using Gnus gcc compiler. It was also found to compile on HPUX using gcc. Note that every code snippet was not individually tested. Contents: What is a socket?Two Types of Internet Sockets Low level Nonsense and Network Theory structsKnow these, or aliens will destroy the planet! Convert the Natives! IP Addresses and How to Deal With Them socket()Get the File Descriptor! bind()What port am I on? connect()Hey, you! listen()Will somebody please call me? 1 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html accept()Thank you for calling port 3490. send() and recv()Talk to me, baby! sendto() and recvfrom()Talk to me, DGRAM-style close() and shutdown()Get outta my face! etpeername()Who are you? gethostname()Who am I? DNSYou say whitehouse. gov, I say 198. 137. 240. 100 Client-Server Background A Simple Stream Server A Simple Stream Client Datagram Sockets Blocking select()Synchronous I/O Multiplexing. Cool! More references Disclaimer and Call for Help What is a socket? You hear talk of sockets all the time, and perhaps you are wondering just what they are exactly. Well, theyre this: a way to speak to other programs using standard Unix file descriptors. What? Okyou may have heard some Unix hacker state, Jeez, everything in Unix is a file! What that person may have been talking about is the fact that when Unix programs do any sort of I/O, they do it by reading or writing to a file descriptor. A file descriptor is simply an integer associated with an open file. But (and heres the catch), that file can be a network connection, a FIFO, a pipe, a terminal, a real on-the-disk file, or just about anything else. Everything in Unix is a file! So when you wan t to communicate with another program over the Internet youre gonna do it through a file descriptor, youd better believe it. Where do I get this file descriptor for network communication, Mr.Smarty-Pants? is probably the last question on your mind right now, but Im going to answer it anyway: You make a call to the socket() system routine. It returns the socket descriptor, and you communicate through it using the specialized send() and recv() (man send, man recv) socket calls. But, hey! you might be exclaiming right about now. If its a file descriptor, why in the hell cant I just use the normal read() and write() calls to communicate through the socket? The short answer is, You can! The longer answer is, You can, but send() and recv() offer much greater control over your data transmission. What next? How about this: there are all kinds of sockets. There are DARPA Internet addresses (Internet Sockets), path names on a local node (Unix Sockets), CCITT X. 25 addresses (X. 25 Sockets that you can safely ignore), and probably many others depending on which Unix flavor you run. This document deals only with the first: Internet Sockets. Two Types of Internet Sockets 2 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Whats this? There are two types of Internet sockets? Yes. Well, no. Im lying.There are more, but I didnt want to scare you. Im only going to talk about two types here. Except for this sentence, where Im going to tell you that Raw Sockets are also very powerful and you should look them up. All right, already. What are the two types? One is Stream Sockets; the other is Datagram Sockets, which may hereafter be referred to as SOCK_STREAM and SOCK_DGRAM, respectively. Datagram sockets are sometimes called connectionless sockets (though they can be connect()d if you really want. See connect(), below. Stream sockets Network Programming with Sockets Essay Example Network Programming with Sockets Essay Socket programming got you down? Is this stuff just a little too difficult to figure out from the man pages? You want to do cool Internet programming, but you dont have time to wade through a gob of structs trying to figure out if you have to call bind() before you connect(), etc. , etc. Well, guess what! Ive already done this nasty business, and Im dying to share the information with everyone! Youve come to the right place.This document should give the average competent C programmer the edge s/he needs to get a grip on this networking noise. Audience This document has been written as a tutorial, not a reference. It is probably at its best when read by individuals who are just starting out with socket programming and are looking for a foothold. It is certainly not the complete guide to sockets programming, by any means. Hopefully, though, itll be just enough for those man pages to start making sense 🙂 Platform and Compiler Most of the code contained within this document was compiled on a Linux PC using Gnus gcc compiler.It was also found to compile on HPUX using gcc. Note that every code snippet was not individually tested. Contents: What is a socket? Two Types of Internet Sockets Low level Nonsense and Network Theory structsKnow these, or aliens will destroy the planet! Convert the Natives! IP Addresses and How to Deal With Them socket()Get the File Descriptor! bind()What port am I on? connect()Hey, you! listen()Will somebody please call me? 1 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html accept()Thank you for calling port 3490. end() and recv()Talk to me, baby! sendto() and recvfrom()Talk to me, DGRAM-style close() and shutdown()Get outta my face! getpeername()Who are you? gethostname()Who am I? DNSYou say whitehouse. gov, I say 198. 137. 240. 100 Client-Server Background A Simple Stream Server A Simple Stream Client Datagram Sockets Blocking select()Synch ronous I/O Multiplexing. Cool! More references Disclaimer and Call for Help What is a socket? You hear talk of sockets all the time, and perhaps you are wondering just what they are exactly. Well, theyre this: a way to speak to other programs using standard Unix file descriptors.What? Okyou may have heard some Unix hacker state, Jeez, everything in Unix is a file! What that person may have been talking about is the fact that when Unix programs do any sort of I/O, they do it by reading or writing to a file descriptor. A file descriptor is simply an integer associated with an open file. But (and heres the catch), that file can be a network connection, a FIFO, a pipe, a terminal, a real on-the-disk file, or just about anything else. Everything in Unix is a file! So when you want to communicate with another program over the Internet youre gonna do it through a file descriptor, youd better believe it. Where do I get this file descriptor for network communication, Mr. Smarty-Pants? is p robably the last question on your mind right now, but Im going to answer it anyway: You make a call to the socket() system routine. It returns the socket descriptor, and you communicate through it using the specialized send() and recv() (man send, man recv) socket calls. But, hey! you might be exclaiming right about now. If its a file descriptor, why in the hell cant I just use the normal read() and write() calls to communicate through the socket? The short answer is, You can! The longer answer is, You can, but send() and recv() offer much greater control over your data transmission. What next? How about this: there are all kinds of sockets. There are DARPA Internet addresses (Internet Sockets), path names on a local node (Unix Sockets), CCITT X. 25 addresses (X. 25 Sockets that you can safely ignore), and probably many others depending on which Unix flavor you run. This document deals only with the first: Internet Sockets. Two Types of Internet Sockets 2 of 26 12. 03. 99 01:21 B eejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. tml Whats this? There are two types of Internet sockets? Yes. Well, no. Im lying. There are more, but I didnt want to scare you. Im only going to talk about two types here. Except for this sentence, where Im going to tell you that Raw Sockets are also very powerful and you should look them up. All right, already. What are the two types? One is Stream Sockets; the other is Datagram Sockets, which may hereafter be referred to as SOCK_STREAM and SOCK_DGRAM, respectively. Datagram sockets are sometimes called connectionless sockets (though they can be connect()d if you really want.See connect(), below. Stream sockets are reliable two-way connected communication streams. If you output two items into the socket in the order 1, 2, they will arrive in the order 1, 2 at the opposite end. They will also be error free. Any errors you do encounter are figments of your own deranged min d, and are not to be discussed here. What uses stream sockets? Well, you may have heard of the telnet application, yes? It uses stream sockets. All the characters you type need to arrive in the same order you type them, right? Also, WWW browsers use the HTTP protocol which uses stream sockets to get pages.Indeed, if you telnet to a WWW site on port 80, and type GET pagename, itll dump the HTML back at you! How do stream sockets achieve this high level of data transmission quality? They use a protocol called The Transmission Control Protocol, otherwise known as TCP (see RFC-793 for extremely detailed info on TCP. ) TCP makes sure your data arrives sequentially and error-free. You may have heard TCP before as the better half of TCP/IP where IP stands for Internet Protocol (see RFC-791. ) IP deals with Internet routing only. Cool. What about Datagram sockets? Why are they called connectionless?What is the deal, here, anyway? Why are they unreliable? Well, here are some facts: if you se nd a datagram, it may arrive. It may arrive out of order. If it arrives, the data within the packet will be error-free. Datagram sockets also use IP for routing, but they dont use TCP; they use the User Datagram Protocol, or UDP (see RFC-768. ) Why are they connectionless? Well, basically, its because you dont have to maintain an open connection as you do with stream sockets. You just build a packet, slap an IP header on it with destination information, and send it out. No connection needed.They are generally used for packet-by-packet transfers of information. Sample applications: tftp, bootp, etc. Enough! you may scream. How do these programs even work if datagrams might get lost?! Well, my human friend, each has its own protocol on top of UDP. For example, the tftp protocol says that for each packet that gets sent, the recipient has to send back a packet that says, I got it! (an ACK packet. ) If the sender of the original packet gets no reply in, say, five seconds, hell re-tran smit the packet until he finally gets an ACK. This acknowledgment procedure is very important when implementing SOCK_DGRAM applications.Low level Nonsense and Network Theory Since I just mentioned layering of protocols, its time to talk about how networks really work, and to show some examples of how SOCK_DGRAM packets are built. Practically, you can probably skip this section. Its good background, however. 3 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Hey, kids, its time to learn about Data Encapsulation! This is very very important. Its so important that you might just learn about it if you take the networks course here at Chico State ;-).Basically, it says this: a packet is born, the packet is wrapped (encapsulated) in a header (and maybe footer) by the first protocol (say, the TFTP protocol), then the whole thing (TFTP header included) is encapsulated again by the next protocol (say, UDP), then again by the next (IP), then again by the final protocol on the hardware (physical) layer (say, Ethernet). When another computer receives the packet, the hardware strips the Ethernet header, the kernel strips the IP and UDP headers, the TFTP program strips the TFTP header, and it finally has the data. Now I can finally talk about the infamous Layered Network Model.This Network Model describes a system of network functionality that has many advantages over other models. For instance, you can write sockets programs that are exactly the same without caring how the data is physically transmitted (serial, thin Ethernet, AUI, whatever) because programs on lower levels deal with it for you. The actual network hardware and topology is transparent to the socket programmer. Without any further ado, Ill present the layers of the full-blown model. Remember this for network class exams: Application Presentation Session Transport Network Data Link Physical The Physical Layer is the ha rdware (serial, Ethernet, etc. . The Application Layer is just about as far from the physical layer as you can imagineits the place where users interact with the network. Now, this model is so general you could probably use it as an automobile repair guide if you really wanted to. A layered model more consistent with Unix might be: Application Layer (telnet, ftp, etc. ) Host-to-Host Transport Layer (TCP, UDP) Internet Layer (IP and routing) Network Access Layer (was Network, Data Link, and Physical) At this point in time, you can probably see how these layers correspond to the encapsulation of the original data.See how much work there is in building a simple packet? Jeez! And you have to type in the packet headers yourself using cat! Just kidding. All you have to do for stream sockets is send() the data out. All you have to do for datagram sockets is encapsulate the packet in the method of your choosing and sendto() it out. The kernel builds the Transport Layer and Internet Layer on for you and the hardware does the Network Access Layer. Ah, modern technology. So ends our brief foray into network theory. Oh yes, I forgot to tell you everything I wanted to say about routing: nothing! Thats right, Im not going to talk about it at all.The router strips the packet to the IP header, consults its routing table, blah blah blah. Check out the IP RFC if you really really care. If you never learn about it, well, youll live. [Encapsulated Protocols Image] 4 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html structs Well, were finally here. Its time to talk about programming. In this section, Ill cover various data types used by the sockets interface, since some of them are a real bitch to figure out. First the easy one: a socket descriptor.A socket descriptor is the following type: int Just a regular int. Things get weird from here, so just read through and bear with me. Know this: there are two byte orderings: most significant byte (sometimes called an octet) first, or least significant byte first. The former is called Network Byte Order. Some machines store their numbers internally in Network Byte Order, some dont. When I say something has to be in NBO, you have to call a function (such as htons()) to change it from Host Byte Order. If I dont say NBO, then you must leave the value in Host Byte Order. My First Struct(TM)struct sockaddr.This structure holds socket address information for many types of sockets: struct sockaddr { unsigned short sa_family; /* address family, AF_xxx */ char sa_data[14]; /* 14 bytes of protocol address */ }; sa_family can be a variety of things, but itll be AF_INET for everything we do in this document. sa_data contains a destination address and port number for the socket. This is rather unwieldy. To deal with struct sockaddr, programmers created a parallel structure: struct sockaddr_in (in for Internet. ) struct sockaddr_in { shor t int sin_family; /* Address family */ unsigned short int sin_port; /* Port number */ truct in_addr sin_addr; /* Internet address */ unsigned char sin_zero[8]; /* Same size as struct sockaddr */ }; This structure makes it easy to reference elements of the socket address. Note that sin_zero (which is included to pad the structure to the length of a struct sockaddr) should be set to all zeros with the function bzero() or memset(). Also, and this is the important bit, a pointer to a struct sockaddr_in can be cast to a pointer to a struct sockaddr and vice-versa. So even though socket() wants a struct sockaddr *, you can still use a struct sockaddr_in and cast it at the last minute!Also, notice that sin_family corresponds to sa_family in a struct sockaddr and should be set to AF_INET. Finally, the sin_port and sin_addr must be in Network Byte Order! But, you object, how can the entire structure, struct in_addr sin_addr, be in Network Byte Order? This question requires careful examinati on of the structure struct in_addr, one of the worst unions alive: /* Internet address (a structure for historical reasons) */ 5 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html struct in_addr { nsigned long s_addr; }; Well, it used to be a union, but now those days seem to be gone. Good riddance. So if you have declared ina to be of type struct sockaddr_in, then ina. sin_addr. s_addr references the 4 byte IP address (in Network Byte Order). Note that even if your system still uses the God-awful union for struct in_addr, you can still reference the 4 byte IP address in exactly the same way as I did above (this due to #defines. ) Convert the Natives! Weve now been lead right into the next section. Theres been too much talk about this Network to Host Byte Order conversionnow is the time for action!All righty. There are two types that you can convert: short (two bytes) and long (four bytes). The se functions work for the unsigned variations as well. Say you want to convert a short from Host Byte Order to Network Byte Order. Start with h for host, follow it with to, then n for network, and s for short: h-to-n-s, or htons() (read: Host to Network Short). Its almost too easy You can use every combination if n, h, s, and l you want, not counting the really stupid ones. For example, there is NOT a stolh() (Short to Long Host) functionnot at this party, anyway.But there are: htons()Host to Network Short htonl()Host to Network Long ntohs()Network to Host Short ntohl()Network to Host Long Now, you may think youre wising up to this. You might think, What do I do if I have to change byte order on a char? Then you might think, Uh, never mind. You might also think that since your 68000 machine already uses network byte order, you dont have to call htonl() on your IP addresses. You would be right, BUT if you try to port to a machine that has reverse network byte order, your program wi ll fail. Be portable! This is a Unix world!Remember: put your bytes in Network Order before you put them on the network. A final point: why do sin_addr and sin_port need to be in Network Byte Order in a struct sockaddr_in, but sin_family does not? The answer: sin_addr and sin_port get encapsulated in the packet at the IP and UDP layers, respectively. Thus, they must be in Network Byte Order. However, the sin_family field is only used by the kernel to determine what type of address the structure contains, so it must be in Host Byte Order. Also, since sin_family does not get sent out on the network, it can be in Host Byte Order.IP Addresses and How to Deal With Them Fortunately for you, there are a bunch of functions that allow you to manipulate IP addresses. No need to figure them out by hand and stuff them in a long with the h_addr); bzero(;(their_addr. sin_zero), 8); /* zero the rest of the struct */ if ((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *);thei r_addr, sizeof(struct sockaddr))) == -1) { perror(sendto); exit(1); } printf(sent %d bytes to %s ,numbytes,inet_ntoa(their_addr. sin_addr)); close(sockfd); return 0; } And thats all there is to it!Run listener on some machine, then run talker on another. Watch them communicate! Fun G-rated excitement for the entire nuclear family! Except for one more tiny detail that Ive mentioned many times in the past: connected datagram sockets. I need to talk about this here, since were in the datagram section of the document. Lets say that talker calls connect() and specifies the listeners address. From that point on, talker may only sent to and receive from the address specified by connect(). For this reason, you dont have to use sendto() and recvfrom(); you can simply use send() and recv().Blocking Blocking. Youve heard about itnow what the hell is it? In a nutshell, block is techie jargon for sleep. You probably noticed that when you run listener, above, it just sits there until a packet arrives. What happened is that it called recvfrom(), there was no data, and so recvfrom() is said to block (that is, sleep there) until some data arrives. Lots of functions block. accept() blocks. All the recv*() functions block. The reason they can do this is because theyre allowed to. When you first create the socket descriptor with socket(), the kernel sets it to blocking.If you dont want a socket to be blocking, you have to make a call to fcntl(): #include #include . . sockfd = socket(AF_INET, SOCK_STREAM, 0); fcntl(sockfd, F_SETFL, O_NONBLOCK); . . By setting a socket to non-blocking, you can effectively poll the socket for information. If you try to read from a non-blocking socket and theres no data there, its not allowed to blockit will return -1 and errno will be set to EWOULDBLOCK. Generally speaking, however, this type of polling is a bad idea. If you put your program in a busy-wait looking for data on the socket, youll suck up CPU time like it was going out of style.A more elegant solution for checking to see if theres data waiting to be read comes in the following secti on on 21 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html select(). select()Synchronous I/O Multiplexing This function is somewhat strange, but its very useful. Take the following situation: you are a server and you want to listen for incoming connections as well as keep reading from the connections you already have. No problem, you say, just an accept() and a couple of recv()s. Not so fast, buster!What if youre blocking on an accept() call? How are you going to recv() data at the same time? Use non-blocking sockets! No way! You dont want to be a CPU hog. What, then? select() gives you the power to monitor several sockets at the same time. Itll tell you which ones are ready for reading, which are ready for writing, and which sockets have raised exceptions, if you really want to know that. Without any further ado, Ill offer the synopsis of select(): #include #include #include int select(int n umfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);The function monitors sets of file descriptors; in particular readfds, writefds, and exceptfds. If you want to see if you can read from standard input and some socket descriptor, sockfd, just add the file descriptors 0 and sockfd to the set readfds. The parameter numfds should be set to the values of the highest file descriptor plus one. In this example, it should be set to sockfd+1, since it is assuredly higher than standard input (0). When select() returns, readfds will be modified to reflect which of the file descriptors you selected is ready for reading. You can test them with the macro FD_ISSET(), below.Before progressing much further, Ill talk about how to manipulate these sets. Each set is of the type fd_set. The following macros operate on this type: FD_ZERO(fd_set *set) clears a file descriptor set FD_SET(int fd, fd_set *set) adds fd to the set FD_CLR(int fd, fd_set *set) removes fd fro m the set FD_ISSET(int fd, fd_set *set) tests to see if fd is in the set Finally, what is this weirded out struct timeval? Well, sometimes you dont want to wait forever for someone to send you some data. Maybe every 96 seconds you want to print Still Going to the terminal even though nothing has happened.This time structure allows you to specify a timeout period. If the time is exceeded and select() still hasnt found any ready file descriptors, itll return so you can continue processing. The struct timeval has the follow fields: struct timeval { int tv_sec; /* seconds */ int tv_usec; /* microseconds */ }; 22 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Just set tv_sec to the number of seconds to wait, and set tv_usec to the number of microseconds to wait. Yes, thats microseconds, not milliseconds.There are 1,000 microseconds in a millisecond, and 1,000 milliseconds in a second. Thus, th ere are 1,000,000 microseconds in a second. Why is it usec? The u is supposed to look like the Greek letter Mu that we use for micro. Also, when the function returns, timeout might be updated to show the time still remaining. This depends on what flavor of Unix youre running. Yay! We have a microsecond resolution timer! Well, dont count on it. Standard Unix timeslice is 100 milliseconds, so youll probably have to wait at least that long, no matter how small you set your struct timeval.Other things of interest: If you set the fields in your struct timeval to 0, select() will timeout immediately, effectively polling all the file descriptors in your sets. If you set the parameter timeout to NULL, it will never timeout, and will wait until the first file descriptor is ready. Finally, if you dont care about waiting for a certain set, you can just set it to NULL in the call to select(). The following code snippet waits 2. 5 seconds for something to appear on standard input: #include #incl ude #include #define STDIN 0 /* file descriptor for standard input */ main() { struct timeval tv; fd_set readfds; tv. v_sec = 2; tv. tv_usec = 500000; FD_ZERO(;readfds); FD_SET(STDIN, ;readfds); /* dont care about writefds and exceptfds: */ select(STDIN+1, ;readfds, NULL, NULL, ;tv); if (FD_ISSET(STDIN, ;readfds)) printf(A key was pressed! ); else printf(Timed out. ); } If youre on a line buffered terminal, the key you hit should be RETURN or it will time out anyway. Now, some of you might think this is a great way to wait for data on a datagram socketand you are right: it might be. Some Unices can use select in this manner, and some cant. You should see what your local man page says on the matter if you want to attempt it.One final note of interest about select(): if you have a socket that is listen()ing, you can check to see if there is a new connection by putting that sockets file descriptor in the readfds set. And that, my friends, is a quick overview of the almighty select() function. More References 23 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Youve come this far, and now youre screaming for more! Where else can you go to learn more about all this stuff? Try the following man pages, for starters: ocket() bind() connect() listen() accept() se nd() recv() sendto() recvfrom() close() shutdown() getpeername() getsockname() gethostbyname() gethostbyaddr() getprotobyname() fcntl() select() perror() Also, look up the following books: Internetworking with TCP/IP, volumes I-III by Douglas E. Comer and David L. Stevens. Published by Prentice Hall. Second edition ISBNs: 0-13-468505-9, 0-13-472242-6, 0-13-474222-2. There is a third edition of this set which covers IPv6 and IP over ATM. Using C on the UNIX System by David A. Curry. Published by OReilly ; Associates, Inc. ISBN 0-937175-23-4.TCP/IP Network Administration by Craig Hunt. Published by OReilly Associates, Inc. ISBN 0-937175-82-X. TCP/IP Illustrated, volumes 1-3 by W. Richard Stevens and Gary R. Wright. Published by Addison Wesley. ISBNs: 0-201-63346-9, 0-201-63354-X, 0-201-63495-3. Unix Network Programming by W. Richard Stevens. Published by Prentice Hall. ISBN 0-13-949876-1. On the web: BSD Sockets: A Quick And Dirty Primer (http://www. cs. umn. edu/~bentlema/unix/has o ther great Unix system programming info, too! ) Client-Server Computing (http://pandonia. canberra. edu. au/ClientServer/socket. html)Intro to TCP/IP (gopher) 24 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html (gopher://gopher-chem. ucdavis. edu/11/Index/Internet_aw/Intro_the_Internet/intro. to. ip/) Internet Protocol Frequently Asked Questions (France) (http://web. cnam. fr/Network/TCP-IP/) The Unix Socket FAQ (http://www. ibrado. com/sock-faq/) RFCsthe real dirt: RFC-768 The User Datagram Protocol (UDP) (ftp://nic. ddn. mil/rfc/rfc768. txt) RFC-791 The Internet Protocol (IP) (ftp://nic. ddn. mil/rfc/rfc791. txt)RFC-793 The Transmission Control Protocol (TCP) (ftp://nic. ddn. mil/rfc/rfc793. txt) RFC-854 The Telnet Protocol (ftp://nic. ddn. mil/rfc/rfc854. txt) RFC-951 The Bootstrap Protocol (BOOTP) (ftp://nic. ddn. mil/rfc/rfc951. txt) RFC-1350 The Trivial File Transfer Protocol (TFT P) (ftp://nic. ddn. mil/rfc/rfc1350. txt) Disclaimer and Call for Help Well, thats the lot of it. Hopefully at least some of the information contained within this document has been remotely accurate and I sincerely hope there arent any glaring errors. Well, sure, there always are. So, if there are, thats tough for you.Im sorry if any inaccuracies contained herein have caused you any grief, but you just cant hold me accountable. See, I dont stand behind a single word of this document, legally speaking. This is my warning to you: the whole thing could be a load of crap. But its probably not. After all, Ive spent many many hours messing with this stuff, and implemented several TCP/IP network utilities for Windows (including Telnet) as summer work. Im not the sockets god; Im just some guy. By the way, if anyone has any constructive (or destructive) criticism about this document, please send mail to [emailprotected] csuchico. du and Ill try to make an effort to set the record straight. I n case youre wondering why I did this, well, I did it for the money. Hah! No, really, I did it because a lot of people have asked me socket-related questions and when I tell them Ive been thinking about putting together a socket page, they say, cool! Besides, I feel that all this hard-earned knowledge is going to waste if I cant share it with others. WWW just happens to 25 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html be the perfect vehicle.I encourage others to provide similar information whenever possible. Enough of thisback to coding! 😉 Copyright  © 1995, 1996 by Brian Beej Hall. This guide may be reprinted in any medium provided that its content is not altered, it is presented in its entirety, and this copyright notice remains intact. Contact [emailprotected] csuchico. edu for more information. 26 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Da teien/Manualz/not ad ramming; Using Internet Sockets/net. htmlBeejs Guide to Network Programming Using Internet Sockets Version 1. 5. 4 (17-May-1998) [http://www. cst. csuchico. edu/~beej/guide/net] Intro Hey! Socket programming got you down? Is this stuff just a little too difficult to figure out from the man pages? You want to do cool Internet programming, but you dont have time to wade through a gob of structs trying to figure out if you have to call bind() before you connect(), etc. , etc. Well, guess what! Ive already done this nasty business, and Im dying to share the information with everyone! Youve come to the right place. This document should give the average competent C programmer the edge s/he needs to get a grip on this networking noise. AudienceThis document has been written as a tutorial, not a reference. It is probably at its best when read by individuals who are just starting out with socket programming and are looking for a foothold. It is certainly not the complete guide to sockets programming, by any means. Hopefully, though, itll be just enough for those man pages to start making sense 🙂 Platform and Compiler Most of the code contained within this document was compiled on a Linux PC using Gnus gcc compiler. It was also found to compile on HPUX using gcc. Note that every code snippet was not individually tested. Contents: What is a socket?Two Types of Internet Sockets Low level Nonsense and Network Theory structsKnow these, or aliens will destroy the planet! Convert the Natives! IP Addresses and How to Deal With Them socket()Get the File Descriptor! bind()What port am I on? connect()Hey, you! listen()Will somebody please call me? 1 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html accept()Thank you for calling port 3490. send() and recv()Talk to me, baby! sendto() and recvfrom()Talk to me, DGRAM-style close() and shutdown()Get outta my face! etpeername()Who are you? gethostname()Who am I? DNSYou say whitehouse. gov, I say 198. 137. 240. 100 Client-Server Background A Simple Stream Server A Simple Stream Client Datagram Sockets Blocking select()Synchronous I/O Multiplexing. Cool! More references Disclaimer and Call for Help What is a socket? You hear talk of sockets all the time, and perhaps you are wondering just what they are exactly. Well, theyre this: a way to speak to other programs using standard Unix file descriptors. What? Okyou may have heard some Unix hacker state, Jeez, everything in Unix is a file! What that person may have been talking about is the fact that when Unix programs do any sort of I/O, they do it by reading or writing to a file descriptor. A file descriptor is simply an integer associated with an open file. But (and heres the catch), that file can be a network connection, a FIFO, a pipe, a terminal, a real on-the-disk file, or just about anything else. Everything in Unix is a file! So when you wan t to communicate with another program over the Internet youre gonna do it through a file descriptor, youd better believe it. Where do I get this file descriptor for network communication, Mr.Smarty-Pants? is probably the last question on your mind right now, but Im going to answer it anyway: You make a call to the socket() system routine. It returns the socket descriptor, and you communicate through it using the specialized send() and recv() (man send, man recv) socket calls. But, hey! you might be exclaiming right about now. If its a file descriptor, why in the hell cant I just use the normal read() and write() calls to communicate through the socket? The short answer is, You can! The longer answer is, You can, but send() and recv() offer much greater control over your data transmission. What next? How about this: there are all kinds of sockets. There are DARPA Internet addresses (Internet Sockets), path names on a local node (Unix Sockets), CCITT X. 25 addresses (X. 25 Sockets that you can safely ignore), and probably many others depending on which Unix flavor you run. This document deals only with the first: Internet Sockets. Two Types of Internet Sockets 2 of 26 12. 03. 99 01:21 Beejs Guide to Network Programming file:///C|/Eigene Dateien/Manualz/not ad ramming; Using Internet Sockets/net. html Whats this? There are two types of Internet sockets? Yes. Well, no. Im lying.There are more, but I didnt want to scare you. Im only going to talk about two types here. Except for this sentence, where Im going to tell you that Raw Sockets are also very powerful and you should look them up. All right, already. What are the two types? One is Stream Sockets; the other is Datagram Sockets, which may hereafter be referred to as SOCK_STREAM and SOCK_DGRAM, respectively. Datagram sockets are sometimes called connectionless sockets (though they can be connect()d if you really want. See connect(), below. Stream sockets