Criteria for essay writing
Tuesday, August 25, 2020
Water Quality; Wastewater Management Essay Example | Topics and Well Written Essays - 500 words
Water Quality; Wastewater Management - Essay Example The wastewater having exceptionally high measure of broke up BOD or COD would require either organic treatment forms, as enacted muck treatment, streaming channels upflow anaerobic slime treatment, or substance treatment units like coagulation methods, filtration with particle trade and so on. These strategies would not be sufficient for complete end of the broke down polluting influences. For instance on account of city wastewater, the auxiliary treatment would brings about the decrease of natural piece of the all out contaminants broke up in it. Then again, the toxins like nitrates and phosphates or bacterial/microbiological defilement would not be completely expelled utilizing these techniques. Henceforth, propelled treatment tasks are furthermore required for the expulsion of the previously mentioned polluting influences (Malzer, 2002). The treatment forms utilized in such circumstances are delegated the tertiary treatment. The strategies are generally nitrification and denitrifi cation units which are likewise natural techniques embraced with the assistance of bacterial mass. Then again, phosphates also need specific treatment units for its expulsion. Further, if the goal is to wipe out the bacterial sullying, sterilization frameworks should be given properly as the tertiary unit activity. Hence the strategies utilized under the optional and tertiary treatment units are of various sorts and each having distinctive reason. In this manner in a run of the mill treatment framework where the auxiliary tasks are reliant on the enacted slime plants, the activities comprise of a progression of bury connected units having a settling bowl where the slop is isolated from the rewarded water, following by muck thickening, ooze drying and ooze removal. The rewarded water from the settling tank denotes the finish of optional treatment tasks the water would even now
Saturday, August 22, 2020
Cancer Care Coursework Example | Topics and Well Written Essays - 1500 words
Disease Care - Coursework Example Actually, vinyl chlorides encourage the improvement of liver sarcomas. The motivation behind malignant growth the study of disease transmission helps in bringing up the territories of circulation of malignant growth and revealing the principle hazard factor that causes and enhances the malignancy cases. Epidemiologic investigation or research gives a distinct, cross-sectional, natural, and efficient examinations that join working on this issue control and exceptionally involved intercession process in overseeing of the disease cases. The previous 56 years has been depicted by a concentrated research in the disease field to uncover the genuine idea of malignancy and along these lines give light on the idea of the hazard factor on malignant growth (Kelvin and Tyson, 2011, p78). Occurrence alludes to various new cases detailed in a fixed timeframe partitioned by the quantity of individuals who are uncovered in danger. For all intents and purposes the time term of study is typically picked to be a year and is alluded to as a yearly rate (Fleishman, 2012, p34). The significance of essential the study of disease transmission in the counteraction of malignancy traces the arrangements of involved intercessions that consistently avoids the advancement of the carcinogenic procedure. This gatherings of the procedure incorporate wellbeing directing and involved training, keeping of item security, guaranteeing of natural controls. The essential endeavors target controlling what may cause the improvement of the carcinogenic cells yet optional controls for the most part manages the treatment or decrease of disease development after recognition or finding. Item security is a solid area of essential anticipation since the vast majority of the synthetic concoctions are the sole reason and initiating component of disease. The avoidance of malignancy, at the essential level, fundamentally puts resources into arranging, assessment and execution of the anticipations strategies involved in the improvement of the understanding ideas that basic on controlling of disease (Wallace and Kelnar, 2009, p56). The essential anticipation is ordinarily intended for the avoidance of malignant growth
Tuesday, July 28, 2020
How to Build a Service Oriented Architecture (SOA)
How to Build a Service Oriented Architecture (SOA) © Shutterstock.com | Bakhtiar ZeinIn this article we focus on the topic of Service Oriented Architecture (SOA). We start with a deep dive in 1) SOA: a description and going then to discuss 2) building a Service Oriented Architecture.SERVICE ORIENTED ARCHITECTURE: A DESCRIPTIONWhat is SOA?SOA or Service-oriented Architecture is a method through which different types of services can interact with each other independently. A service is a self-contained part of the functionality, and several services can be combined to provide use and functionality of a software application on a large scale. What SOA does is that it makes it simpler for software parts on PCs that are connected to a network to interact and cooperate. The design pattern of SOA is such that applications components in it can offer services to other such components mostly over a network. Each and every computer system can run any number of services, each of which is built to exchange information with any other different serv ice in a network without human help.In business terminology, SOA is a set of business-aligned IT services which together address the goals and processes of the business company. The structural design of SOA makes sure that there is an alignment with the requirements of the business as well as the technological solution of the same.The major elements of SOAHere are the major elements of SOA:SOA Drivers SOA drivers or enterprise business drivers include things like competition, strategy, regulatory forces and market forces. All these things come together to drive the business architecture and to give a shape to business-wide performance managementSOA enablers The five main SOA enablers are Enterprise business model, Business performance optimization, Portfolio Rationalization, Enterprise Semantics definition and Key performance indicators. Having a business model is important for the correct alignment of services with the aims and goals of the business. The semantic information mode l gives the common and general business related information for a given enterprise. Key performance indicators or KPIs make the assessment of the impact of SOA possible and make the measurement of business processes easier. On the other hand, portfolio rationalization makes consolidation and simplification of applications, data and infrastructure possible.SOA Implementation As far as implementation is concerned, business services and processes are the main aspects. Business processes are mostly associated with business goals and objectives of operations whereas, on the other hand, business services must be well aligned and are critical to flexible and successful SOA implementation. Some of the other aspects related to SOA implementation are Enterprise content repositories, semantic messaging and integration services. The information represents the data resources of the company, and this data is passed in the form of documents that provide a kind of semantic messages between service s and processes.SOA Support All the functions and elements from the existing applications and systems are made available and usable to the services with the support of some integration services that take off covers from the existing functions via new service interfaces.The Main Principles of SOAThe following is the list of the main principles of SOA:Service architecture The physical layout or design of individual services that surpass all the resources that were used by a service.Service composition architecture All the services developed using service-oriented design methods are composition centric, and this is their main feature. This architecture, therefore, is the composition of individual architectures of various services.Service inventory architecture This architecture is formed from the service inventory blueprint where the service inventory is made up of services that automate the procedures of businesses.Service-oriented enterprise architecture This type constitutes of composition, service as well as inventory architectures.The Evolution of SOA ConceptMonolithic design This design was related to relatively unstructured procedural codingObject and structure oriented design This is the design that involves program units based on functionalities.Client-server design (two-tier design) This is the concept of distributed design and is related to bundling of functionalities into two tiers.Distributed object design (multitier design) This design involves object interactions in a heterogeneous environment and distributed object design.Component object model architecture This is a design in which there is an aggregation of items into logic based parts with strongly types as well as a well-defined interface.Service oriented architecture This is a design that involves interactions and communications between coarse-grained services with standard interfaces for a flexible interoperations.SOA and JAVAMany developers think that SOA, as well as web services , are synonymous with one another, but this is not true. They may also believe that it is just not possible to build SOA without using web services but in reality, SOA is a design principle but web services are a kind of an implementation technology. This means that SOA can be in fact built without making use of implementation technology of a certain kind. But Java is another kind of a traditional technology which can be used to develop or build Service Oriented Architecture.The main aim of SOA is to develop a loose coupling between modules, and an application can be built where the modules are not coupled with one another too tightly. This kind of a structure can be built or formed with the help of JAVA.What are the characteristics of SOA?Loose connection The services in SOA are linked together loosely to form one connection. This gives a presupposition to the modicum of the interdependence between each service. The main idea is to reduce the interdependence to the level where com patibility is still maintained.The standardized services interface One basic requirement of SOA is the need for standardization of interfaces as well as details. The details must include which data is needed, how a service can be used and how rules have to be applied.Reusability In SOA, reusability of services is possible down the process chain by other parties as well and for other types of purposes also.Findability of a service Another characteristic is that a service must easily be found in order to use it. To all consumers, service repositories are made available, and such repositories consist of the interface and implementation method of service.Service autonomy Every service must be able to work and function independently. This term points to those services that are self-sufficient and are capable of managing resources, logic, and the environment on their own.Capacity for service orchestration This is a process where an individual service is combined with other such servi ces to result in larger business processes or units. This is a further characteristic or requirement for SOA.Statelessness of services Performance of services is based on the concept that a defined service is rendered. This takes into account retention of data but only if the requirement is specified or requested especially.Advantages and benefits of SOABetter returns on investment One of the greatest benefits of SOA is that it offers a superb return on investment. Since the process involves the creation of robust layers, each of these service layers offer a better return on the investment that was done to create the software.Code mobility This is yet another important benefit of SOA and is possible because there is a location transparency in Service Oriented Architecture. Most clients do not care where the services are located because there is a dynamic binding as well as the lookup to services. This means that the businesses using SOA can move services to different machines or move it to external service providers.The reusability Another advantage of SOA is that the various codes and services can be used over and over again. There is the convenience of run-time service reuse, and it is as easy as finding a service in the directory and binding to it. The developers do not have to worry about platforms and other incompatibilities.Support for various client types Any company can use multiple client types and multiple clients to access a service in SOA. This is because in such a structure or concept, the layers have been divided into service, and client layers and various client types are simpler to implement.A higher level of availability Several servers have several cases of services using them due to the fact that SOA support location transparency. This means that the overall availability is very high. For example, if a machine or a part of a network stops working or has some issue, the requests can be redirected to other services without the client kno wing it or being bothered by it.Fewer defects This is a major advantage of SOA. The probability of defects is much lower, and the overall testing is a lot better due to published interfaces of services that can be tested easily. More testing translates to a greater level of accuracy and fewer defects.SOA ChallengesLack of Testing Space One of the biggest challenges in SOA is the lack of testing space. In a typical architecture, there are no well-formed or sophisticated tools or methods to test a headless service such as a message or database service. The main objective of SOA is to offer agility to companies and businesses. But due to lack of horizontal trust, one needs to invest in a testing framework that would make the challenge easier.Manage Services Metadata This is a common and very obvious challenge of SOA. Managing the services metadata is not just tough but often very complicated. A service based architectural space involves services interacting with each other by exchan ging message. In such a scenario, a single services may sometimes have millions of messages generated. Managing these many services can become very difficult especially when the services are delivered by different companies and departments within a company. This creates many trust issues.Providing right levels of the security Another challenge of SOA is providing appropriate levels of security. The application-managed security is not the correct method or model for securing services because security models designed into applications cannot suffice when the application shows itself to others.Interoperability This becomes a crucial aspect of SOA implementations. Often, in the pursuit to reduce or decrease the interdependence of services, the compatibility between them may reduce but the dependence has to be reduced to such a level that compatibility can still be maintained.Vendor hype There is a significant vendor hype related to SOA, and this creates a certain level of undue expec tations. While there are many advantages of SOA, it can have several disadvantages as well. For example, SOA does not guarantee a reduction in IT costs and does not even promise improvement in agility of systems. Thus, it would be better if there was a clear distinction between hype and reality.BUILDING A SERVICE ORIENTED ARCHITECTURESOA FrameworkTo understand how SOA is built, you will first need to understand what its framework is.SOA is viewed as 5 different horizontal layers which are:Consumer interface layer-These are the apps that access service or app interfaces.Business process layer-This is a layer that is a service that represents business use-cases as far as applications are concerned.Services Many services are clubbed together for creating a whole enterprise.Service components These are those components or parts that are used to build services like technological interfaces and technical libraries, etc.Operational systems This is the layer that contains technical patte rns, data models, and data repository, etc.The following are the vertical layers of SOA framework which are applied to and supported by the horizontal ones:Integration layer This layer consists of protocol support or platform integration, data integration, application and service integration, etc.Quality of service The factors that comprise of the quality of service include availability, security, performance and others.Informational This layer mainly does the job of providing business related information.Governance This layer or IT strategy layer is governed by horizontal layers in order to reach capability, as well as operating model, as needed.SOA Implementation Framework (SOAIF)SOA implementation needs and requires run-time infrastructural software as well as tools. This can be collectively referred to as service-oriented architecture implementation framework or SOAIF. This concept aims for a comprehensive framework that offers all kinds of technology which a business may re quire to not only build but also run SOA. An SOAIF consists of and includes both run-time and design-time capabilities. It also includes software functionality that a company may need to run an SOA and also build it, including service-oriented:ModelingIntegrationToolsManagementSecurityProcessesApproaches to SOAThere are three major types or methods or approaches that have been emerging for club information, disparate and systems in a business. As different service providers and businesses race towards providing solutions to customers and consumers, these approaches help to meet the requirements for coarse-grained, loosely clubbed and asynchronous services.1. The Enterprise Service BusThe first approach that helps to build and implement an optimal SOA is the enterprise service bus or ESB. This approach helps to coordinate and arrange the different elements that are in the form of distributed services on a network. This approach considers the systems to be discrete and distributed services that connect to one another through message oriented infrastructure that is asynchronous. This kind of a message-oriented infrastructure makes it possible to have loosely coupled connections between independent services or modules.2. Business Process ManagementMany companies, for many years now, have tried to solve business process problems by the implementation of Business Process Management approach. This approach takes into consideration the IT assets and systems as activities or tasks that participate in well synchronized and well-orchestrated business procedures. BPM tools are mainly used at the time of modeling and designing procedures rather than using them to construct processes that can reach integration objectives. This is the main challenge of BPM. By BPM solutions on their own are enough to meet SOA requirements because they do not consist of the runtime environment that is needed for loosely coupled modules.3. Service Oriented IntegrationThe third and the last approach to proper implementation of SOA is the service-oriented integration approach. This particular approach makes use of the architectural guiding rules or principles to build an environment or ecosystem of services that businesses can combine dynamically and create superior level processes that can meet ever changing and evolving requirements. This approach moves past tightly coupled and brittle modules by creating a distinction between the consumer and producer of a service. It thus imposes the aspect of loose coupling that is needed to implement SOA properly to meet business requirements. Even this approach by itself isnât sufficient to guarantee long time running interactions between services.The Best practices for building an SOAWhile building an SOA, one must follow some of the best and most advantages practices. These practices are given as follows:Implementation technologies are much hyped, and one must remember not to jump to them because of their popular ity. One must consider carefully whether or not the web services make more sense for their requirement and need. It is important to remember that building service-oriented applications by making use of technologies like RMI may be more suitable for a businessâs case rather than web services.One must remember not to create or build very tightly linked or coupled modules as this leads to a brittle set up or infrastructure.It is important to maintain interoperability and for these, one must follow the WS-I best practices.If you donât see any sense in using web services, then there are many other alternative options as well which can be chosen.
Friday, May 22, 2020
The Issue Of Mineral Rights Essay - 1954 Words
As a first-time homebuyer in the Dallas/Fort Worth area, I thought I had very carefully prepared myself for all that the process would involve, including gathering income and financial documentation, qualifying for a mortgage, arranging for a thorough inspection, evaluating needs and desires from a home and finding a reputable agent to represent my interests. One area I never considered, however, was the issue of mineral rights. To be perfectly honest, although I d heard the term, I d never given consideration to what it actually meant. But that all changed in the middle of my home buying process - and I d like to share with you the knowledge I ve gained through extensive research I completed to protect my own rights and the rights I would possess as a soon-to-be homeowner. According to property law, two different forms of rights exist in any real property: surface rights and mineral rights. Surface rights refer to any structure erected above the surface or sub-surface structures th at do not exceed a certain depth, as well as rights to use all surface property surrounding structures in accordance with zoning ordinances. Mineral rights refer to mineral substances below a certain depth and the way in which they are preserved, explored or extracted. These mineral substances can include natural gas, oil, or any other substance in common use today that can be mined or otherwise extracted from below the surface. Local laws set the depth below which surface rights terminateShow MoreRelatedThe Mining Act 1990830 Words à |à 4 Pages1990, has a significant role in protecting Ontarioââ¬â¢s vast mineral resources and brings forth a set of policies in which promote responsible mining development and extraction. The provincial government plays an integral role in the provinces mining industry because the Act requires that all mineral claims must be recorded and accepted by the Crown which from then the two parties discuss a lease fee for the mineral rights. After loca ting a mineral claim in an area deemed open by the Crown, there are twoRead MoreCadia Case Analysis Essay1726 Words à |à 7 PagesHoldings Pty Ltd and Newcrest Operations Ltd (NOL) owned land in New South Wales, granted to them by the State of New South Wales under the Mining Act 1992 (NSW). From July 1998 to March 2008, Cadia conducted mining operations in which it recovered minerals including copper and gold, and paid royalties to the Minister pursuant to the Mining Act 1992 (NSW). The Minister referred to the Case of Mines[1], claiming that the mine owned by Cadia was a ââ¬Å"royal mineâ⬠containing gold that belonged to the CrownRead MoreBare Minerals vs Pur Minerals851 Words à |à 4 PagesBare Minerals versus Pur Minerals Kristina McClary English 112 March 4, 2010 In the last ten years the cosmetics has transcends from chemical base to natural from foundations and blushes to lip color and eye makeup. Women have many choices in cosmetics brands, such as department specialty discount stores brands. Due to the growing popularity of natural cosmetics in demand specialty cosmetic companies like Bare Minerals and Pur minerals were introduce to answer. Bare Minerals the first toRead MoreMandated Disclosure Of Conflict Minerals : Does It Work?1626 Words à |à 7 PagesSection 1502 Mandated Disclosure of Conflict Minerals: Does it work? In short form, Section 1502 of the Dodd-Frank Wall Street Reform and Consumer Protection Act mandates disclosure of conflict minerals originated in the Democratic Republic of the Congo (DRC) to the Securities Exchange Commission (SEC) and due diligence in sourcing those conflict minerals. Conflict minerals include gold, tantalum, tin, and tungsten, which are used in many popular consumer products used and manufactured throughoutRead MoreThe Law Of General Application1414 Words à |à 6 PagesMINISTER FOR MINERALS AND ENERGY 2013 (4) SA 1 (CC) The facts of the case were that ââ¬Å"Sebenza (Pty) Ltd bought coal rights from the liquidators of Kwa-Zulu Collieries (Pty) Ltd for R1 048 800 on 2 October 2001 and registered them in its name. S was not the owner of the land on which the coal was located. [14] On 1 May 2004 the MPRDA came into effect. S became the holder of an unused old order right on that date. This happened in terms of item 8 of schedule II to the MPRDA. Unused old order rights were inRead MoreA Brief Note On Mining And Its Impact On The Environment Essay1376 Words à |à 6 Pagesespecially in Canada.Canada has one of the largest mining supply sectors in the world,more than 3 700 companies and is one of the largest mineral suppliers.Canada is first place for Potash,second place for uranium and niobium,third place for cobalt,aluminum,tungsten and platinum group metals (M.A.C,n.d.).Mining is important because it is the process of discovering the minerals that are used to make steel,,jewelry,lead,and many other types of metals used everyday.Mining may be useful but it has a negativeRead MoreThe Oil And Natural Gas1240 Words à |à 5 Pagesa piece of land does not mean he or she has the right to set up a lease for the drilling of oil or gas. Before mining and drilling was possible the ownership of land was simple, the owner owned the surface, subsurface and the air above the surface. Today it is possible for an owner to only own the surface of their land, this is called surface rights. In order to set up a drilling lease the owner must posses the surface rights and the mining rights which means that they own wants beneath the surfaceRead MoreThe Mining Of Conflict Minerals1427 Words à |à 6 Pages Conflict minerals are used in many commercially available items, such as many electronic devices and much jewelry. These minerals are Tin, Tantalum, Tungsten and Gold. Mines, in which these minerals are collected, are often sites for violent armed groups, hence the name conflict minerals. This problem is especially prominent in the Democratic Republic of Congo, but also takes place in many other nations such as the Central African Republic, Tanzania and Angola as well. These nations often do notRead MoreEthics And The Ethical Dilemma1252 Words à |à 6 Pagesthey mostly depends on manufacturers in Asia. But the manufacturers never knew where the minerals they use come from. The Apple company used conflict minerals which is against human rights and they extracted illegally from Congo mineral deposits. It is a great mistake done by them. This reflected the ethics of Integrity and Leadership .Two things that reflect these ethics are that using of conflict minerals and the second is not to reveal this to the manufacturers. Apple started facing pressureRead MoreOur Nutrition And Food We Eat1251 Words à |à 6 Pagesconditions (Axelson, Federline and Brinberg). Around a large portion of the wellbeing heap of food is attributable to dangerous water, unaltered sanitation and cleanliness. Interestingly, in industrialized countries, over-food and food wellbeing issues, including food borne disorders impacting human wellbeing furthermore impacts joined with cultivating creation schemas, are pervasive concerns. There is furthermore a foremost rate of under food among destitute, and a higher inconvenience of both
Saturday, May 9, 2020
Events that Lead to the Civil War Essay - 1754 Words
Events that Lead to the Civil War The civil war is known for its issues of slavery and the conflict between the north and the south. The split in the union can be traced as far back as the 1810ââ¬â¢s, just as the industrial revolution was beginning. With the industrial revolutionââ¬â¢s effects on the north and the south caused the economy to split. The north became more industrialized; the south started relaying more on agriculture. In the north, machines, interchangeable parts, and mass production took over, and started the building of factories. These first factories were used for making textiles and later evolved to manufacturing a wide variety of goods. This sparked opportunity for jobs, and with immigrants flooding in form Europe itâ⬠¦show more contentâ⬠¦In 1828, A Tariff was passed to help try to protect New England Manufactures. The tariff was as high as 45% to 50% of the original European price. The north wanted these higher tariffs so their products could compete on the same level as the cheaper foreign products. Opponents of the tariff called it the Tariff of Abomination. Southerners were opposed to the tariff because they exported cotton and other materials to Europe in exchange European goods were imported to America. Southerners claimed it was an indirect tax on their region of the United States. Southerner s began to ask for states rights. South Carolina even went as far as to ask for the tariff taken off or they would succeed. The tariff was lowered by Congress. The north didnââ¬â¢t need to buy as many foreign products as the south because they were very self-reliant. After the United States went to war with Mexico, a win meant more land but, the Missouri Compromise of 1820, only dealt with the Louisiana Territory. In 1846, David Wilmot, of Pennsylvania, proposed an answer. His plan said: any land acquired from Mexico was to be free land. The House passed the bill, but it was shot down in the Senate. It was able to pass in the House because Northerners controlled it but it was unable to pass in the Senate because Southerners controlled it. This was a big issue because it showed that there was little that either side could do to pass a law that oneShow MoreRelatedPre-Civil War: Events that Lead to the Abolition of the Slave Trade and Slavery768 Words à |à 4 Pagesslavery. Prosser and a group of his followers would procure armor and weapons then try and take over the city, thus freeing them from slavery. Unfortunately before they could execute the plan, him and some of his followers were put to death, an event that would prove to be a catalyst to the uprising. Following their deaths and many more to come, Africans slaves then would attempt to flee from their plantation or masters and run for freedom. Slaves in the southern states flee to the North justRead MoreTaking a Look at the American Civil War896 Words à |à 4 PagesMany events during the mid-1700-1800s provoked the civil war because of the contradicting ideas between the northern states and the southern states. The conflict between the north and south that led to the civil war includes economic, social, and political events. At the meantime, slavery arose as a huge debate between the pro-slavery and anti-slavery faction. Fierce debates had sparked between the north and south states because of the southern statesââ¬â¢ agrarian based economy. The geography in theRead MoreThe Legacy Of The Vietnam War967 Words à |à 4 Pagesdistinction of being a year in which civil unrest, social progress, and the state of change were the norm, and featured events that affec ted not only America, but the world as a whole. With the condition of America at the time, society was going through changes that would go on to have massive impact on how the world would progress, with some of these events having effects years afterwards. The Vietnam War had been going on for nine years up to this point, and the events that would occur during 1968 wouldRead MoreThe Rights of Women in the Unites States from 1846 to the Civil War789 Words à |à 4 PagesThere were wars and many political changes that lead to better opportunities in society for women and slaves. Many things happened between 1846 and the civil war in the early 1850ââ¬â¢s woman started to revolt and realize there was more to life then just being human puppets. Then shortly after that the parties started to separate and states began to fear that the president would take away their slaves so in fear of that they started to separate from the united states. The last events lead to an unwantedRead MoreKatherine Ramjit. Mr. Staccone. T2 History. April 28Th,1194 Words à |à 5 PagesStaccone T2 History April 28th, 2017 Through What Events Was Slavery The Main Cause Of the American Civil War of 1861-1865 Some may argue that the main causes of the Civil War was The Missouri Compromise, the Kansas-Nebraska Act, the Compromise of 1850 and or much more. There is a multitude of reasons or causes that people can argue about what really started the War. One important factor to take in account is that most events leading up towards the Civil War really revolved to slavery. Slavery can be definedRead MoreNorth South Tensions Before Civil War868 Words à |à 4 PagesAjit Beeki Ms. Jones North-South Tensions before Civil War The Civil War was not a spontaneous conflict, rather it was the culmination of various events in American history that were in the two decades preceding it. These events exposed a rift in American society which would eventually lead to the Civil War. Among these events were the Kansas-Nebraska Act and Mexican-American War. Both of them lead to a highly polarized reactions from Northerners and Southerners in the slavery debate. In the endRead MoreThe American Revolution1190 Words à |à 5 Pagesdescendants of participants in the war and created a focus on the importance of ancestry, leads the belief that there were another motivating factor behind an organization of this type. Influencing the founders of the D.A.R. was both the Civil War and the rising immigration to the United States. The Civil War ended with slaves becoming freemen and citizens, affecting the definition of citizenship. Also the war increase patriotic drive in the citizens which directly lead the forming of th e patrioticRead Morecivil war963 Words à |à 4 Pages Prompt: There were numerous events and crises during the 1850ââ¬â¢s that contributed to the advent of the civil war. Choose three and analyze the relative significance of each in contributing to the advent of the Civil War. During the time period of the mid 1800ââ¬â¢s there was a great deal of growing tension between the northern and southern states. Many northerners were abolitionists and were anti slavery, the northerners didnââ¬â¢t want to outlaw slavery completely but wanted to put an end to slaveryRead MoreCause Of The Civil War On America1290 Words à |à 6 Pages1301 Professor Harris December 3, 2015 Causes of the Civil War Lasting from 1861-1865 The Civil war: one of the most bloodiest and alienated wars in the American History has had a tremendous impact on our past society, and modern as well. In the early 1800ââ¬â¢s the United States accomplished harmony, alliance, and unification, eventually causing sectionalism to flourish. This controversy led to the famous bloody war, known as the Civil war. While the south wanted to separate, and become one, theRead MoreWhat Events Sparked The Civil War?779 Words à |à 4 Pages Mrs. McGee English 2 27 April 2015 What Events Sparked the Civil War? ââ¬Å"We here highly resolve that these dead shall not have died in vain.â⬠Abraham Lincoln spoke this during the time the Civil War had ended. There were several major events that helped spark the Civil War; Uncle Tomââ¬â¢s Cabin, John Brownââ¬â¢s Raid, Lincolnââ¬â¢s Election, and the Battle at Fort Sumter. The Civil war was one of the hardest fought battles in American history. In 1852, Uncle Tomââ¬â¢s Cabin
Wednesday, May 6, 2020
The Secret Circle The Divide Chapter 8 Free Essays
The kitchen was shadowy and quiet when Cassie stepped inside. Her mother wasnââ¬â¢t home, and she was glad. She didnââ¬â¢t want to have to explain why she was hauling bricks out of the fireplace. We will write a custom essay sample on The Secret Circle: The Divide Chapter 8 or any similar topic only for you Order Now Just up the block, Diana was retrieving the tiara and whatever other materials theyââ¬â¢d need to complete the resuscitation spell. And a little farther down Crowhaven Road, the rest of the group was somehow going to convince Melanie to allow them to bring her great-auntââ¬â¢s body to the lighthouse. Before this year, Cassie had never even seen a real dead body, and now she was going to put her hands over one and try to bring it back to life. The fireplace wasnââ¬â¢t such a creative hiding spot for the bracelet, Cassie knew, but it had worked successfully for so many years, why try to think up someplace different? Deep inside its gaping stone mouth, she found the silver document box just as sheââ¬â¢d left it. And when she removed its ancient lid, the bracelet glistened inside, as if it were celebrating the sudden, surprising light. Cassie allowed herself to admire the braceletââ¬â¢s beauty for only a second. She ran her fingers over the intricate design on its rich silver surface and felt its weight in her hands. But then Diana called to her from outside. ââ¬Å"Be right there!â⬠she yelled, and ran upstairs to quickly change into her ceremonial white shift. Once she was dressed and ready, she found Diana waiting for her on the front porch swing with a large cotton sack at her side. Sheââ¬â¢d also changed into her ceremonial shift, but there was a composure to Dianaââ¬â¢s appearance that Cassie could only aspire to. Even under all this stress, Diana remained in control. Cassie reached for her hand, hoping some of the strength would rub off Dianaââ¬â¢s skin onto hers. And somehow it did. A few moments of holding Diana close calmed her. ââ¬Å"Weââ¬â¢re doing the right thing,â⬠Diana said. ââ¬Å"We need Constance.â⬠Cassie remembered what a refuge Constance had been since she lost her grandmother. And all the afternoons sheââ¬â¢d spent in her parlor, learning new spells and studying ancient rituals. Constance was the only connection to the old ways the Circle had. ââ¬Å"I know we are,â⬠Cassie said in her most courageous voice. ââ¬Å"Iââ¬â¢m ready to go.â⬠ââ¬Å"Okay, everyone, letââ¬â¢s get started.â⬠Diana emptied the cotton sack onto the table when they arrived at the lighthouse and immediately began reading directions from her Book of Shadows. It didnââ¬â¢t surprise Cassie how everyone automatically turned to Diana in moments like this ââ¬â moments when it really mattered. She would always be the most natural leader among them, no matter what. ââ¬Å"The body should be entirely covered in white cloth of two layers,â⬠Diana read aloud to Adam. ââ¬Å"With head and face veiled in tull e.â⬠She gestured to a pile of fine white netting on the table. Adam nodded. ââ¬Å"Iââ¬â¢ll take care of it,â⬠he said. Nick, Chris, and Doug pushed all the furniture to the roomââ¬â¢s perimeter. Melanie kneeled in the center beside the covered body. Cassie helped Deborah drape the windows with purple linens. Diana approached Faye carrying two golden censers. ââ¬Å"We have to fumigate the chamber with sage and frankincense,â⬠she said. Faye had changed into her ceremonial black shift, and she was already wearing the green leather garter with its seven silver buckles. She accepted the censers from Diana and then called Sean over to tend to the chore. ââ¬Å"Whereââ¬â¢s the diadem?â⬠she asked. Diana nodded over to Melanie, sitting solemnly with the diadem on her head. ââ¬Å"Sheââ¬â¢s the one who gets to wear the Tools tonight,â⬠Diana said. ââ¬Å"Sheââ¬â¢s doing the conjuring. The rest of us are her support.â⬠Even Faye couldnââ¬â¢t disagree that Melanie should be the one leading this spell, but she still tore the garter from her leg with fury before walking it over to Melanie. Cassie followed close behind her, removing the bracelet from her wrist on her way. In a few minutes, the room had been properly prepared, and Diana called for the ritual to begin. ââ¬Å"Faye and Cassie, will you do the honors of casting the circle according to my instructions? Forgive me if I go slowly ââ¬â this text is really hard to read ââ¬â but Iââ¬â¢ll do my best. Is everyone ready?â⬠Cassie looked around the dimly lit room. She wasnââ¬â¢t the only one who seemed nervous, but nobody was about to back out now. Melanie appeared to be in a cloudy-eyed daze, but she looked more beautiful wearing the Master Tools than Cassie had ever seen her. Diana cleared her throat and began reading aloud. ââ¬Å"A magic circle is to be formed upon the ground with an ink of soot and port wine. A second circle is formed half a foot within the first.â⬠Together Cassie and Faye formed the circles around Melanie and Constance, using the chalice of ink Diana had prepared. ââ¬Å"And within there,â⬠Diana continued, ââ¬Å"cast a triangle, the center of which will serve as the resting place of the deceased and primary conjurer.â⬠Cassie and Faye formed the triangle within the circles, outlining Melanie and Constance. ââ¬Å"Everyone get inside,â⬠Diana said. ââ¬Å"And then Iââ¬â¢ll close the outer circle with the four layers of protection.â⬠Quickly the group arranged itself, kneeling upon the outer circleââ¬â¢s perimeter as Diana called on the elements. ââ¬Å"Powers of Air, protect us,â⬠Diana called out. ââ¬Å"Powers of Fire, protect us.â⬠Cassie closed her eyes and listened. ââ¬Å"Powers of Water, protect us.â⬠Diana enunciated each syllable with precision. ââ¬Å"And finally,â⬠she said, ââ¬Å"I call on the powers of Earth to protect us.â⬠Diana then joined the circle beside Cassie and continued reading from her Book of Shadows. ââ¬Å"To commence, the conjurer must light a black candle and cast it over the body seven times thereon, calling the name of the spirit to be raised.â⬠All eyes turned to Melanie now. Cassie wondered if she had the strength to do it. But the Tools glistened, and Melanieââ¬â¢s posture straightened as she lit the candle and passed it over the white sheet, calling out, ââ¬Å"Great-Aunt Constance, Constance Burke, hear us.â⬠Diana continued, ââ¬Å"Then from a golden chalice of dried amaranth flowers, sprinkle the body and its surrounding area.â⬠While Melanie did the sprinkling, Diana said, ââ¬Å"Melanie, repeat after me: Thou who art mourned, see now the nature of this mourning.â⬠And Melanie repeated, ââ¬Å"Thou who art mourned, see now the nature of this mourning.â⬠Cassie felt her eyes fill with tears as Diana chanted: This is the spell that we intone Flesh to flesh and bone to bone Sinew to sinew and vein to vein Constance shall be whole again They all concentrated hard, harnessing their powers together as one. Cassie could sense an energy rising up from the center triangle, webbing out to each member of the group, linking them all together in a maze of light. Diana read aloud, ââ¬Å"After a moment of silence and concentration, uncover the face of the deceased. Then call to the spirit again, affectionately. Say ââ¬ËWelcome.'â⬠With quivering hands, Melanie gently unveiled Constanceââ¬â¢s face. ââ¬Å"Great-Aunt Constance,â⬠she said. ââ¬Å"Welcome.â⬠ââ¬Å"The body will stir,â⬠Diana read. ââ¬Å"The eyes will open, and then the desired awakening.â⬠The room crackled with energy. Cassie could feel it zipping and twisting around her in spirals, but she wasnââ¬â¢t afraid of it anymore. The air around them warmed, and Cassie could see the life flickering back into Constanceââ¬â¢s face slowly, like the rising sun. Then a shape began to form. Cassie noticed it faintly at first in the glow on Constanceââ¬â¢s forehead, but then it grew bigger and brighter until it stood out like an iridescent bruise. It was most definitely a symbol, a primal-looking mark resembling two crooked U-shapes within a hexagon. Then everything went dark. The light that had come to Constanceââ¬â¢s face, the symbol, the candles ill uminating the room ââ¬â all of it disappeared, as if a heavy blanket were dropped from the ceiling, snuffing the room to death. Diana lit her lantern and held it up to Melanieââ¬â¢s grief-stricken face. Her great-aunt Constance was still dead. And now she had to experience her death all over again. ââ¬Å"The spell didnââ¬â¢t work,â⬠Laurel said. ââ¬Å"But it was working.â⬠Dianaââ¬â¢s eyes franticly searched the group. ââ¬Å"Didnââ¬â¢t you all feel it?â⬠ââ¬Å"Yes, of course,â⬠Adam said. ââ¬Å"I donââ¬â¢t understand what went wrong.â⬠Faye was silent but looked just as confused as the others. Adam spoke out again. ââ¬Å"Is there anything more to the spell, Diana? Does it say anything else in your book?â⬠Diana squinted at the bottom of the page sheââ¬â¢d been reading, then turned to the next page, and then turned it back again. ââ¬Å"Itââ¬â¢s nearly ill egible,â⬠she said. ââ¬Å"But thereââ¬â¢s a scrawled line here at the bottom edge.â⬠She held her lantern close to the bookââ¬â¢s tiny wording. ââ¬Å"It says, ââ¬ËShould nothing result, and this witch hath been true . . .ââ¬â¢ and then it stops. Whatever it said next got smudged out.â⬠ââ¬Å"Smudged out?â⬠Faye grabbed the book from Dianaââ¬â¢s hands to have a look for herself. ââ¬Å"How could something so important be smudged out?â⬠ââ¬Å"Itââ¬â¢s a three-hundred-year-old book,â⬠Adam said in Dianaââ¬â¢s defense. ââ¬Å"Itââ¬â¢s not that hard to believe.â⬠Cassie wondered if she was the only one who saw the symbol appear on Constanceââ¬â¢s forehead. Or had she imagined it? Over the echoes of Melanieââ¬â¢s sobs, she knew it wasnââ¬â¢t the right time to ask. Constance was lost to them forever. It was late by the time Cassie got back home, but her mother was awake, lying on the sofa in her nightgown. She sat upright as soon as Cassie stepped in from outside. ââ¬Å"Are you all right?â⬠she asked. ââ¬Å"Yes,â⬠Cassie assured her, closing and locking the door behind her. ââ¬Å"Howââ¬â¢s Melanie?â⬠ââ¬Å"Sheââ¬â¢s been better.â⬠Cassie pulled her jacket tightly closed, not wanting her mother to see she was wearing the white shift. ââ¬Å"And Constance?â⬠Cassie hesitated. She realized her mother was eyeing the Master bracelet on Cassieââ¬â¢s left wrist. ââ¬Å"You know then,â⬠Cassie said. ââ¬Å"About the resuscitation spell.â⬠Her mom nodded and gestured for Cassie to join her on the sofa. ââ¬Å"I just figured,â⬠she said. ââ¬Å"Did it work?â⬠At first Cassie simply shook her head and took off her coat. But she wanted to be able to tell her mom everything, even about the symbol she saw ill uminating Constanceââ¬â¢s forehead. And for once she did, without holding anything back for her motherââ¬â¢s benefit. Her mother surprised her by listening, really listening this time. She didnââ¬â¢t change the subject or become so overwhelmed with fear that Cassie had to worry about her more than herself. Until she mentioned the symbol she saw appear on Constanceââ¬â¢s forehead. ââ¬Å"The symbol,â⬠Cassie said, ââ¬Å"looked like something primal. Like two bent U-shapes inside a hexagon.â⬠Cassie noticed the alarmed look that flashed across her motherââ¬â¢s face. ââ¬Å"What is it?â⬠Her mother shook her head. ââ¬Å"Not two U-shapes,â⬠she said. ââ¬Å"One. A W.â⬠Cassie didnââ¬â¢t understand what she was hearing. ââ¬Å"W, as in Witch,â⬠her mother said. Cassie was breathless. Her mother closed her eyes for a moment and when she reopened them they looked as grim as two black coals. ââ¬Å"I know what went wrong with the spell,â⬠she said. ââ¬Å"Thereââ¬â¢s a way a witch can be killed that can never be reversed. But thereââ¬â¢s only one kind of person who can do it.â⬠ââ¬Å"Who?â⬠Cassie asked. ââ¬Å"What kind of person?â⬠ââ¬Å"A witch hunter,â⬠her mother said. How to cite The Secret Circle: The Divide Chapter 8, Essay examples
Tuesday, April 28, 2020
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
Subscribe to:
Posts (Atom)