Thursday, October 31, 2019

Management and Organisational Behaviour Assignment

Management and Organisational Behaviour - Assignment Example A myriad of factors which contribute to chaos in an organisational setup and tarnish OB will also be identified. High absenteeism rate and rotten work attitudes are among the basic factors for polluting an organisation’s environment and stem from negative OB. On the other hand, involvement of staff in the change process amidst other steps can foster a culture that has a high rate of workers’ satisfaction and will to achieve big feats. For this purpose, this report will stress a deep understanding of OB in relevance to job satisfaction, motivation and work attitudes by taking example of Apple Inc.2.0 How Influential Are Motivation and Job Satisfaction in Directing OB?It is an undeniable reality that a motivated and satisfied workforce is a critical asset for any organisation (Chen 2010, p. 66). Such a workforce helps in sustaining the richness of OB yielding multiple benefits for a business. Numerous grave repercussions in reference to OB start dominating the scene when nonchalant managers do not make wise investments in inculcating a sense of organisational commitment in the employees (Perry 2010). In contrast, motivated employees are more satisfied with their jobs, are happier personally, and show a staggering tendency to improve their organisation’s productivity. It is because of the highly deterministic role played by job satisfaction and motivation that leaders and managers should invest more time in implementing various valuable theories of OB to steer the workforce in the right direction. The type of attitudes employees have towards work and how content they are speaks a lot about how likely are any infringements on OB. 3.0 How Successful Is Apple Inc. in Terms of Workers’ Attitudes and Job Satisfaction? Apple Inc. is a well-reputed and widely popular example of OB management done right because this large business organisation has made significant contributions to making employees feel included and valued at the workplace. Foun ded in 1976 by Steve Jobs and Steve Wozniak, this company originally only specialised in personal computers (Harrigan 2003, p. 258) but due to constant hard work and never undermining emotional and psychological needs of its employees, it soon became a symbol of sophistication and one of the most influential names on the face of Earth. A good

Tuesday, October 29, 2019

Crossdressing and Tranvestism Essay Example for Free

Crossdressing and Tranvestism Essay This critique is based on the video â€Å"Hide and Seek† by Group 29. It is about cross dressing. Cross-dressing represents the act of wearing clothing commonly associated with the opposite sex, including various forms: (1) underwear only, (2) clothes but no makeup or wig, (3) clothes, makeup and wigs, and (4) trying to â€Å"pass† as a woman. There are different terms to address the people who cross-dress, such as cross dresser (CD), transvestite (TV), Drag Queens (normally gay and exaggerated) and female impersonators (actors who play women). However, it is important to note that cross dressing is not identical or relevant to transgender, gender identity and willingness to become the opposite sex. The transvestites only want to dress like the other gender for some time. Statistics have revealed that about 3% to 5% of the populations are transvestites, while the majority of them are heterosexual. According to medical research, the underlying factors of becoming a transvestite are due to family background, the surrounding environment and social learning. Most of the cross-dressers face difficulties such as fears to be discovered by family, friends and partners. However, this is because the society is generally against cross dressers and often described them as insane or having mental problems. For example, in Hong Kong, the society is unfriendly towards cross dressing and the general public does discriminate against the transvestites. Analysis The content of this video is analyzed in four aspects as follows:- Title Titled as â€Å"Hide and Seek†, the video portrays the fear of a male cross dresser to be discovered by his girlfriend. The authors would like â€Å"to show the cross dressers are hiding themselves away but at the same time seeking the identification. † From the video, the message that the cross dressers hope to hide their habit is clearly shown. When the Katherine returns home and opens the door, Joe is very frightened that his cross dressing behaviour is revealed by Katherine. However, the second statement â€Å"at the same time seeking the identification† cannot be directly or passively interpreted from the video, since Joe only exclaims his love towards Katherine when his cross dressing is about to reveal from the sub-title â€Å"There is another girl. But he still loves you. † This statement does not prove that he is seeking for identification, approval or tolerance from Katherine. There is also a lack of any scene to show that Joe, being a transvestite, is searching for identification and recognition from other people. Moreover, if the tile â€Å"Hide and Seek† was not stated and explained by the authors, the audience would not identify the specified meaning of the title. It otherwise gives the impression to audience that the title relates to the hide and seeks between Joe and Katherine when Joe is cross dressing and Katherine is returning home. Plot In the video, the first part shows the actions of a man, Joe and his girlfriend, Katherine at the same time. Joe is dressing on as a woman in the washroom. First, he puts on make-up: Applying mascara and putting on red lip gross. Second, he wears on a shocking pink flower dress, black leggings and bra. Then he caresses his breast in front of the mirror. At the same time, Katherine is going back home, entering the entrance, getting into the lift and opening the doors with keys. When Joe realizes Katherine is coming back with the sounds of keys, he quickly washes his face to remove the make-up, takes off his bra and leggings, and finally uses a cotton pad with make-up remover to remove his eye shadow, eye line and mascara. At the same instant, Katherine is searching for him. Then, Joe walks to Katherine. Katherine is suspicious that â€Å"Why there is smell of fragrance? † and â€Å"Was there another girl? † Joe’s eyes are enlarged to show his fear and speechlessness. â€Å"There is another girl. † â€Å"But he still loves you. † Here, it would like to bring out that Joe does not have any extramarital relations. The â€Å"another girl† means Joe himself. Even though he has the cross dressing behaviour, he still loves Katherine. Character There are two characters in this video: Joe and Katherine. First of all, Joe is a transvestite. I think that his acting is realistic to justify the role of his character. He has acquired mastery of wearing on all the female attire and make-up. After dressing up as a female, his smile and stroke of hands on the breast in front of the mirror can effectively bring the message that he really feels satisfied with it and enjoys transvestism. Moreover, when Katherine is puzzled with the fragrance form Joe, the facial expressions from Joe is vivid to show his fear to reveal he is actually having transvestism at home. Regrettably, there is one shot which looks rather strange. After wearing on the black stockings, he twists his legs and moves his toes. Though the authors describe that scene as â€Å"cross dresser looked at his leg† and they describe it as using the cross dresser’s point of view, and â€Å"it can make the audience understand the mindset of the cross dresser: happy and pleased with his feminine look†, that shot gives an impression to me that Joe was having leg fatigue at that moment so that he moves his legs and toes to relieve the pain. Also, the shot is not basically taken in the cross dresser’s point of view. It is a shot from vertical direction. So, that show does not make me understand the mindset of Joe. To better improve the above scene, the video camera should be put at the angle from Joe’s eyes. And his facial expressions when he is happy and pleased with the feminine look should be filmed. Furthermore, the facial expression of Katherine is not quite realistic and cannot make the audience to understand what she feels. In the shot Katherine has got back home, she searches for Joe elsewhere. Finally when she finds out Joe, she should be feeling suspicious and puzzled why there is a scent of fragrance, according to the wordings â€Å"Why there is smell of fragrance? † However, the facial expression of Katherine gives an impression to me that she is drowsy or just wakes up. Her countenance makes the audience confused about what is going on in the video. With the following wordings â€Å"Was there another girl? † the audience can eventually get the message that Katherine is suspicious with Joe to have another partner. Props In the video clip, plenty of female props are employed to show the symbols of cross dressing. For example, mascara, red lip gross, face powder, cosmetic brushes, black stockings, bra are used. These are the representative symbols of a female. Generally male would not use these things. And the myriads of cosmetic kits in the washroom are adequate to show that Joe wants to dress up to be an attractive and pretty woman. In fact, I feel that the props used in the video are strongly relevant to the theme. They are constructive to bring out the message that Joe is cross dressing and the elements of cross dressing are clearly identified. After watching this video, one can understand what transvestism is and how the transvestite dress in the opposite. In my opinion, to further elaborate the image of a transvestite, except the clothing and make-up, Joe can also wear wigs and high heels to make him more feminine. Music Concerning the music part, there is merits and demerits in the video clip. To begin with, when Joe is putting on mascara and lip gross, the music is quite relaxing and cheerful. However, the music becomes wary and suspicious when he is putting on other cosmetics in the washroom. It is a bit inconsistent that the background music for similar instance of make up is so contrasting. In my opinion, the wary music should start when the camera shot moves to the lobby of the building, which implies that Katherine is coming back. In this way, it can let the audience knows that some dangerous instance is about to begin. On the other hand, the speed of the music in the later part is effective to show that sequence of the video. The music becomes increasingly faster when the climax is reached. The speed is useful to show that Joe is so fear to be discovered by his partner of cross dressing because to many people, cross dressing is something abnormal and should be corrected. Interpretation According to the description from the authors, the aims of video are to let â€Å"people who are too busy and have no time to figure out what cross-dressing is could immediately understand the feeling of cross-dresser and understand they are not monster or insane. Their acts are only pleasure-seeking. † And they believe that the video is â€Å"the most effective way to bring a sense of reality to the readers: how the cross -dresser feel when he is cross-dressing; his deep fear of being discovered and the confrontation faced by the couple. † I think that the video clip is effective to bring out the aforementioned aim of the presentation. In particular, the background music and the facial expression from Joe are realistic and let the audience understand the feelings of the cross dressers. However, normal audience without knowledge to transvestism could not understand the nature of it and disregard the transvestites as insane, since there is only one statement â€Å"But he still loves you. † to show that transvestites would not change their love towards lovers. Meanwhile, there lacks any information or implication to prove that the transvestites are indeed normal as ordinary people. So, this video is not useful to educate to eradicate biases towards the transvestites once communicated to the public. It only broadens the knowledge of acts by cross dressers and their inner feelings to audience. In my view, the video should include information to educate the public to accept the transvestites and feel comfortable and easy to live with them. For instance, we can portray a scene that a cross dressers is having cross dressing and his wife lives with him happily and does not mind it. I think that there should be other scenes to portray the daily life of transvestites, and thus the audience can get an implication that the cross dressers are normal as well. Transvestism is only their habit and it would not harm other parties. This is because I feel that the society is full of discrimination towards the transvestites. They are usually related to abnormal or insane behaviour, mental problems or crimes like rape, indecorum. There should be strong and forceful publications to assure the general public that the transvestites are not insane as they may prescribe. In a nutshell, the message from the video can be partially communicated, and it can only be communicated to audience who already has basic knowledge of transvestism. Otherwise, the audience may still think the cross dressers are insane after getting known to their act. The choice of taking videos to show the implied message of the authors is quite suitable. The way and steps of cross dressing can be clearly identified and shown to audience. It makes the audience understand what the meaning of cross dressing is. Also, audience can understand the feelings of cross dresser after reading this video that they usually perform it secretly and do not want their family, partner and friends to know it. With the help of the additional wordings, the audience can further consolidate the idea of this video. So I think that the aims of authors to use video: â€Å"A good video could be eye-catching and effectively delivered a thought-provoking idea in the readers’ mind. † is justified. A man cross dressing to act as a female is quite an innovative idea and the wordings shown at the end of the video can help the audience to understand the transvestites still love their partners even though they have this habit. Conclusion The video produced by Group 29 â€Å"Hide and Seek† can effectively communicate to the audience how the transvestites do in cross dressing and their fear to be revealed by partners. However, this video is not sufficient to educate the readers to accept transvestism such that transvestites are ordinary people like everyone. Reference Chow, L. S. Hide and Seek by Lai Shan Chow. Retrieved December 13th, 2008, from CITE Mahara: http://mahara-broadening. cite. hku. hk/view/view. php? id=76

Sunday, October 27, 2019

Marketing Analysis and Planning at HSBC

Marketing Analysis and Planning at HSBC This report highlights the market segmentation of the HSBC credit card in India. The organisation segments the market on the basis of geographic locations and in view of income, lifestyle and behavioural traits. The product has been majorly targeted to the existing customers of the bank and the shopaholics at the Westside store. The bank also emphasises on increasing credit card-spends and customer satisfaction by offering distinct product types and elite additional benefits unlike its industry rivals. The brand image and service excellence of the organisation has positioned its credit card at an elevation. The marketing mix strategy executed by the bank coils strength to the market position of its credit card. HSBC has designed its credit card to satisfy the needs of every individual in the respective market segment by offering six different card types. The demand for credit card is increasing in the country as more people prefer plastic money over hard cash. Hence, they are willing to pay the optimum price for the card usage. The massive presence of the entity gives an advantage over the competitors and provides convenience to the customers. The report also emphasises on the success of cobrand association with the Westside store and the effective marketing strategies implemented by HSBC. The consumer engages in complex buying behaviour due to numerous similar product options. The effective and efficient marketing mix implemented by the bank echoes positivity on the buyers behaviour towards the credit card. The product satisfies the consumer needs and wants, cost, convenience and communication aspect enhancing the buyers inclination towards the product. Finally, the report critiques the marketing strategy executed by the organisation. It also sketches the key marketing facts and suggests future marketing plans which might help in accelerating growth. 1.1 Description of the Organisation The HSBC group in India was founded in October 1853 when the Mercantile Bank of India, China and London was established in Mumbai. With the authorised capital of INR 5 million, the mercantile bank opened branches in Chennai, London, Colombo and Kandy. By 1855, the bank expanded operations in Kolkata, Canton, Singapore, Hong Kong and Shanghai. The HSBC Group serves around 100 million customers worldwide through around 8,000 offices in 87 countries and territories in Europe, the Asia-Pacific region, the Americas, the Middle East and Africa. With assets of some USD 2,418 billion at 30 June 2010, HSBC is one of the worlds largest banking and financial services organisation. HSBC is marketed worldwide as the worlds local bank. (About us, www.hsbc.co.in) The HSBC Group is committed to the five core business principles of outstanding customer service: effective and efficient operations, strong capital and liquidity, prudent lending policy and strict expense discipline. 2. The market segment of HSBC credit card HSBC isolates the various broad segments within the market and follows segmented marketing. The company divides the market on the basis of creditability. It offers several card types to different market segment adopting clustered preferences. The chart below illustrates HSBCs bases for segmenting: C:UsersPrashantDesktopUntitledaa.jpg The consumer market has been classified on the grounds of different geographical units i.e. states, cities and regions. The main focus is to target urban and sub-urban markets needs and preferences. With the economic growth in the country, double income has become a common scenario in most families resulting in high spending power. HSBC divides the market on the basis of their income and the purchasing power, occupation and social class. Buyer under the common segment group may have different psychographic profiles bases personality and lifestyle. HSBC and Westside offer the cobranded card that is designed to supplement the lifestyle and is regarded as mark of prestige and recognition. The consumer market has further been segmented on the basis of the buyers attitude, knowledge, usage and response to the product. 2.1 Product Targeting HSBC targets the existing customers of the bank from Personal Banking, Assets and Investments and Personal Finance Services (PLB, AIQ PFS) through open market acquisition bases their creditability. HSBC amalgamates its customer base, while amplifying revenue from within the existing customers by majorly increasing their spending on the card instead of hunting for new prospects. The bank can afford new cards, but not at the expense of non-performing assets (NPA). The bank majorly engages in cleaning-up on credit card portfolio and emphasis on retained growth. The bank also considers the credit cards for upgradation to superior card types bases the income criteria. The chart below shows the income eligibility criteria (GBP) for its card types: Source- www.hsbc.co.in There is no income eligibility criterion for HSBC Premier credit card as the existing cards are upgraded to Premier bases card performance and creditability. Furthermore, HSBC targets the Westside store shoppers covering the entire age group in the market. With the acceleration in urbanisation, the rise in customer density area is evident thus enabling efficient utilisation of resources by reaching same number of consumers with minimum number of store outlets. The consumers are in the middle to high range income groups as the products in the store are moderately priced. HSBC Credit card operations, which keep a hawks eye on demographics, are swooping down on shopaholic consumers through the cobrand association with the Westside store. 2.2 Market Positioning and Major Competitors HSBC has a competitive advantage over its counterparts as it engages in offering better, cheaper and newer products and services. It incorporates the customer-benefit approach and product-class approach in order to position its product overcoming the industry rivals. Major Competitors: Citibank Credit Card Standard Chartered Credit Card SBI Credit Card ICICI Credit Card Axis Bank Credit Card HSBC differentiates its credit card from its competitors bases four dimensions: Product Differentiation The HSBC credit card provides special features like fuel surcharge waiver and exclusive rewards programme. The petrol fuel surcharge waiver is an elite feature on HSBC credit card which undermines the similar product offered by the market competitors. The rewards programme on HSBC credit card gives bonus points to the cardholder on every purchase that can be redeemed for annual fees, gifts, gift vouchers, charities and JPmiles (Jet Airways Jet privilege account). Along with these features, HSBC Westside Co-branded card is packed with benefits from both the HSBC and Westside. The card offers privileges and superior savings for a memorable shopping experience unlike its competitors. The HSBC credit card is globally accepted at over 18 million establishments worldwide and over 1 lakh establishments in India. The card has access to cash, round the clock, at over 700000 ATMs worldwide. HSBC endeavours password protected payment facility on the Internet at no additional cost. Moreover, the card comes with the zero lost card liability after the loss of card has been reported to the HSBC. Service Differentiation The cardholder is provided with the usage and service guide along with the credit card to safeguard consumer from any misuse of the product. Moreover, HSBCs international connectivity gives it competitive advantage over a similar product available in the market. The post-sale service is also an integral aspect that a consumer looks for before buying a product. HSBCs preamble is to ensure that the customer get the best of service. The cardholder may contact the customer service channels i.e. phone banking service, email or visit the nearest HSBC branch for any probes. The quality of service offered by HSBC provides a brink to its credit cards market position over the industry rivals in the market. Image Differentiation An established brand name is the result of HSBCs continuous identity building programs and service excellence. The logo of the bank signifies that the doors of the Hongkong and Shanghai Banking Corporation are open for business. The symbol of hexagon representing the six quadrants has an instant recognition and bagged a distinct place in the target customers mind. The same has also worked into brand advertisements in conveying the company personality. At the same time, the banks focus is to create a professional and elegant unified ambience across establishments. There is an exclusive Premier Service desk in selected branches to ensure extra comfort and convenience for its valued customer. The organisation has always believed in playing an active role in the community it serves. At HSBC, corporate sustainability is not mere generosity. It takes its Corporate Sustainability (CS) role seriously and helps create an environment where business and nature can flourish hand in hand. Its MicroFinance lending initiative launched in April 2005 has already benefited almost 9000 poor households in Andhra Pradesh giving them the hope of a sustainable livelihood. (HSBC, www.superbrandsindia.com) Majorly, all the banks offer similar offers and features in the product though; it is HSBCs brand name that creates a difference. Personnel Differentiation HSBC has a strong competitive advantage through hiring and training the better individual that its competitors do. The market segment by HSBC is commendable and targeting market bases financial stability is opt for the industry type as there is huge risk involved. Since, the Indian economy to an extent has recovered from the recession; the bank can initiate offering credit cards to new customer bases. The New to Business (NTB) consumer group can be arbitrated bases their credit history and financial stability within formulated limitations using forecast based risk management. Otherwise, the bank ensures service excellence, local presence and strong market position that undermines its rivals. 3. Marketing Mix Developed by HSBC Supports Its Market Position for Credit Card HSBC devises marketing activities and instils the marketing-mix strategies to influence its business partners along with the prospect consumer. Marketing activities are aimed to create awareness, communication and deliver value to the consumer. 3.1 Product The bank offers different product types for every consumer with different needs and wants. The core product benefit of the credit card is the 52 days free credit period for repayment of purchases. The credit card also comes with the cash advance facility wherein the customer can withdraw cash within the specified cash credit limit. The HSBC credit card types currently in the market are as follows: HSBC Classic credit card HSBC Gold credit card HSBC Platinum credit card HSBC Premier credit card HSBC Westside Cobrand Classic credit card HSBC Westside Cobrand Gold credit card With the HSBC Credit Card the consumers can avail the Balance Transfer which allows them to transfer other credit card outstanding dues for repayment at lower interest rates. Furthermore, the HSBC credit card comes with the Loan on Phone facility to convert the purchase into easy instalments. The bank also has cobrand association with CPP Assistance Services Private Limited to safeguard the cardholders interest in event of card loss, theft and related fraud. The CPP (Card Protection Plan) shields the loss of important cards valuable documents including the other credit, debit, ATM, membership or loyalty cards. Furthermore, the role shoppers can also apply upto three additional credit cards for their spouse, parents, siblings and children. 3.2 Price The HSBC credit card has been priced high compared to the most of the competitors in the market. The consumer does not hesitate to opt for the card at offered price considering the brand name and the additional features of the product. The bank charges annual fee towards the card usage which is levied to the cardholders account in the anniversary month and a joining fee on some card types that is levied at point of sale. From time to time, the bank offer cards with no joining fee and cards free from annual fee for life to select customers. The bank may offer 50% discount on the fee bases the creditability of the prospect and the existing customer. 3.3 Place The enormous International presence of the bank ascertains to be a marketing advantage. It endeavours ease of access to bank services to the cardholder even on an international travel. The existing customers of the bank (PLB, AIQ, and PFS) can directly approach any of the branches for credit card application. However, the bank has also established various distribution channels across country i.e. Direct Selling Agents (DSAs) who generates business for the bank under a mutual agreement. Moreover, the banks cobrand association with Westside store has concentrated the target prospect of the bank and enriched its local presence. The consumer can apply for HSBC Westside credit card by visiting any of the Westside store in the region. The Westside store has an enormous presence in the country that ensures that prospect consumers are at ease to reach the product. 3.4 Promotion HSBC focuses on establishing sound communication with the consumer and implement Direct Marketing strategies. The bank advertises the credit card through various marketing means like Email Telemarketing, trade magazine advertising, hoardings, brochures and cobranding. The bank also attempts to create a positive image of the product to ensure word of mouth strategy works for the product. The Westside association has proved propitious for the bank in conquering the target market base. The card is being majorly marketed by cobranding with other business partners (e.g. pizza hut, movie theatres) in form of discounts and coupons to existing cardholders. From time to time, the bank launches the cash back scheme on card usage or on purchases with associated business partners to retain the existing cardholders and lure the prospect. E.g. the bank is offering 5% -10% cash back on purchase using HSBC credit card with the merchant MakeMyTrip (India) Pvt. Ltd. (Travel Agency). The strategy of offering different product types expands HSBCs market horizons and also ensures convenience and sound communication. HSBC views email marketing as a vital component of their overall marketing mix, enabling them to communicate with their customers in a highly targeted way.CPP insurance offered by the bank safeguards the consumer liability for misuse before reporting the card as lost. However, the bank can also offer a card type that requires a passcode on manual swipes like it offers secure pay for online purchases. This will enhance security and the bank would expand its customer base by attracting the consumer group who do not opt for credit card due to the risks involved. 4. Marketing Mix implemented by HSBC influences Buying Behaviour for its Credit Card As the product is one time buy and is long-term association, the consumer engages in complex buying behaviour. The studies show that similar social class exhibit similar buying behaviour. The banks strategy to offer different product types influences the buyers behaviour to opt for the respective product types. The basic core product is identical to the similar product being offered by the industry rivals. However, the distinct product type and additional exclusive features associated with HSBC credit card allures the esteem-seekers who look for class, brand and snootiness. CPP insurance on the credit card safeguards the buyer from the perceived financial risk. Also, the EMI facility towards purchase is more likely to generate magnetizing effect on the buyer. This is also a well-known fact that in spite of increased interest rate and annual fee levied, the demand for credit card is rising. In the last decade in India, the usage of plastic money encouraged the young middle class to defy the Hindi adage Dont stretch your feet beyond your sheet which is another way of saying, Live within your means. (The swipe and spend economy, p.4) Hence, the pricing strategy opted by HSBC has been quite successful to attract the target consumer who associate the product with prestige and reputation. The bank might fail to allure the consumers who look for cost benefit and whose interest is only in the cashless purchase and credit facility. However, the bank should offer a card type without any joining or annual fee with the core product benefit for full market coverage. Many people have a psychology to correlate the price of the product with its quality and brand name the costlier the better. Such consumers are likely to have positive approach while making a purchase decision. C:UsersPrashantDesktopaaa.jpg The 4 Cs associated with the 4 Ps As the HSBCs tagline goes the Worlds Local Bank the bank ensures the same substantiates to be true with its massive presence in the country and worldwide. The Marketing Mix variable Place has been designed by the bank as such it delivers customer benefit effectively. It provides ease of access to the consumers unlike any of the competitors in the Indian market. Hence, the contended comforters who ponder the convenience and service would consider the product over its substitutes. Thereafter, as the credit cardholders need continuous association and post-sale services, the self-actualizers would understand the benefit of massive presence of the entity. HSBC engages in personalized promotion through direct marketing that enhances effective communication with the consumer and develops loyalty and trust towards the brand. The Email and Telemarketing adopted by HSBC has been the wisest strategy to approach the existing customers of the bank. HSBC is a big brand name and a buyer will have a tendency to buy the HSBC credit card if the reference group or the influencer is currently using the same. The word of mouth strategy works well for these buyers. The family members or friends of the existing customers are likely to choose HSBC credit card over its rivals. The bank emphasises on associating with brands that is most popular by all in the target consumer group to expand its market horizon. There will be no market for product that everybody likes a little, only for products that somebody likes a lot. (Kotler.P, Marketing Management p.251) HSBCs association with popular brand develops a positive image for its product and the consumer having preference for the associated brand would develop positive image towards HSBC. 5. Conclusion HSBC credit cards are among the most popular and top-rated credit cards in India. The product has been designed as per the market requirement and caters to the needs and wants of every individual with different product attributes, brand image and additional benefits. Furthermore, the bank focuses on operational excellence, customer intimacy and product leadership to enhance its market position over its industry rivals. The product is moderately priced and ensures convenience to the buyer. HSBCs cobrand association with Westside and collaboration with strong business partners creates positive buyers approach towards the product.

Friday, October 25, 2019

Essay --

The fictional short story by Kurt Vonnegut entitled Harrison Bergeron takes place in a dystopian future. Vonnegut chooses to make the story a satire in order to raise questions concerning how desirable social equality is within this world and how far society will go to achieve it. Like many dystopian, bleak, futuristic worlds, Vonnegut presents very clear aspects of how society is influenced by propaganda and the extent to how powerful a tool propaganda can be. After reading and analyzing this story, I will attempt to explain how Kurt Vonnegut’s life could have influenced his position on propaganda found within this short story. Furthermore, these elements will be matched to those common propaganda strategies discussed in this class and relate how this may impact any modern society. Vonnegut's experience as a soldier and prisoner of war had a defiant influence on his work. He served as a private and was captured during the Battle of the Bulge in World War II. He was chosen as a leader of the POWs captured because he spoke a little German. After telling the German guards "what [he] was going to do to them when the Russians came,† he was beaten and had his position as leader taken away. Vonnegut was one of the lucky ones to survive an attack in a meat locker used by the Germans as a detention facility. Vonnegut said that the aftermath of the attack was "utter destruction" and "carnage unfathomable." This experience was the inspiration and central theme for many of his other books including Harrison Bergeron. The Germans put the surviving POWs to work, breaking into basements and bomb shelters to gather bodies for mass burial, while German civilians cursed and threw rocks at them. Harrison Bergeron is what seems to be a negative po... ...y to show just how absurd a life living with handicaps can be. The handicap system is a metaphor that tries to bash the ideas of communism that he undoubtedly incorporated from history using Hitler’s Germany and Cold War Russia as examples of how this system is flawed. The satire is further enforced by the elements of propaganda that he uses in the story. The television is the medium in which all people in society use to get their information. It is a powerful tool and Vonnegut has the entire story’s setting be only around the television to show just how much people rely on it. He also shows how propaganda has conditioned people to follow what the State wants them to do by appealing to the people’s logic that no one person should be than another. A good idea in principle, but in action, it causes a lot of harm and only benefits the State or the people in control. Essay -- The fictional short story by Kurt Vonnegut entitled Harrison Bergeron takes place in a dystopian future. Vonnegut chooses to make the story a satire in order to raise questions concerning how desirable social equality is within this world and how far society will go to achieve it. Like many dystopian, bleak, futuristic worlds, Vonnegut presents very clear aspects of how society is influenced by propaganda and the extent to how powerful a tool propaganda can be. After reading and analyzing this story, I will attempt to explain how Kurt Vonnegut’s life could have influenced his position on propaganda found within this short story. Furthermore, these elements will be matched to those common propaganda strategies discussed in this class and relate how this may impact any modern society. Vonnegut's experience as a soldier and prisoner of war had a defiant influence on his work. He served as a private and was captured during the Battle of the Bulge in World War II. He was chosen as a leader of the POWs captured because he spoke a little German. After telling the German guards "what [he] was going to do to them when the Russians came,† he was beaten and had his position as leader taken away. Vonnegut was one of the lucky ones to survive an attack in a meat locker used by the Germans as a detention facility. Vonnegut said that the aftermath of the attack was "utter destruction" and "carnage unfathomable." This experience was the inspiration and central theme for many of his other books including Harrison Bergeron. The Germans put the surviving POWs to work, breaking into basements and bomb shelters to gather bodies for mass burial, while German civilians cursed and threw rocks at them. Harrison Bergeron is what seems to be a negative po... ...y to show just how absurd a life living with handicaps can be. The handicap system is a metaphor that tries to bash the ideas of communism that he undoubtedly incorporated from history using Hitler’s Germany and Cold War Russia as examples of how this system is flawed. The satire is further enforced by the elements of propaganda that he uses in the story. The television is the medium in which all people in society use to get their information. It is a powerful tool and Vonnegut has the entire story’s setting be only around the television to show just how much people rely on it. He also shows how propaganda has conditioned people to follow what the State wants them to do by appealing to the people’s logic that no one person should be than another. A good idea in principle, but in action, it causes a lot of harm and only benefits the State or the people in control.

Thursday, October 24, 2019

Nuremberg Laws against the Jews Essay

The Nuremberg Laws were aimed at preserving the purity of the German race. One of the intentions of the Nuremberg Laws was to provide for who was considered to be a Jew or what it meant to be a Jew. This paper therefore examines the Nuremberg Laws, with an aim of answering the comparative question of what it meant to be a Jew according to the laws. The Nuremberg Laws stemmed from the Nazi Racial Legislation of 1935, which was aimed at upholding the perceived Germanic racial superiority, and promoting it as such. According to Hoss (2013), the national identity in Nazi Germany was required to hold an extremely more superior race. As Stimson (2013) points out, the German racial superiority was expected to be free from the Jews’ contamination. Hoss (2013) points out that during Nazi Germany, the Germans were considered better than Jews, and so the former was required to act in a manner that annihilated the latter. It is for this reason that Nuremberg Laws were formulated to define the identity of the Jews and minimize their contamination of the perceived German racial superiority, all in the hope of safeguarding the German nation for the entire future and upholding the perceive purity of the German blood (Ward & Gainty, 2011). Article 5 of the Nuremberg Laws provided an elaboration of who was to be considered as a Jew. For instance, under Article 5(1) of the Nuremberg Laws, a person was to be considered as a Jew if he or she was a descendant of at least three grandparents who were racially full Jews. Article 5(1) was to be read together with the second sentence of part 2 of Article 2 of the Nuremberg Laws. Article 5(2) of the Nuremberg Laws also provided that a person shall be considered as a Jew if both of his or her parents were full Jews (Ward & Gainty, 2012, p. 332). Under the statute of these formed laws (i. e. the Nuremberg Laws), a person was deemed to have descended from two full Jewish parents, if (a) he or she was a member of the Jewish religious community at the time the Nuremberg Laws came to force, or joined the said community after the laws came into force; (b) he or she was in a marriage relationship with a Jew at the time the laws come into force or entered into such a marriage after the laws had come into force; (c) he or she was born to at least a Jewish parent in a manner provided under Section 1, and if the marriage from which he or she is an offspring was constructed consequent to the coming into force of the Law for the Protection of German Blood and German Honor; and (d) he or she was an offspring an extramarital relationship, that involved a Jew, in the sense of Section 1, and was to be born outside wedlock after the 31st day of July, the year 1936 (Ward & Gainty, 2012). Section 1 of the Nuremberg Laws prohibited any form of marriage relationship between German nationals or kindred blood and Jew. Such marriages were to be considered illegal and against section 1 of the Nuremberg Laws even if, for purposes of evading the law, they were concluded outside Nazi Germany. An individual who happened to be a Jew as provided under Article 5 of the Nuremberg Laws, and as has been explained highlighted in the previous paragraphs, was prohibited, under Section 1 of the Laws, from contracting any marriage relationship with a German national or kindred blood, whether within Nazi Germany or overseas (Ward & Gainty, 2012,). Similarly, Section 2 of the said laws prevented any Jew from entering into any outside marriage with German nationals or kindred blood. According to Hoss (2013) this was aimed at protecting the superiority of the German nation and preserving the purity of the German blood by ensuring that no child of German origin was born outside wedlock, and worse still, with a Jewish parent, since the Jews were not expected to mingle with the German nationals. The Nuremberg Laws did not target the Jews within the context of marriage per se, but also sought to limit the rights of the Jews in terms of free and fair management of their households. For instance, under Section 3 of the Nuremberg Laws, no Jew was allowed to employ a female German national or kindred blood as a domestic worker (Ward & Gainty, 2012). This was construed by Hoss (2013) as a way of preventing incidents of master-servant abuses (e. g. sexual abuse of female German national domestic servants by their Jewish masters), and which could, in some cases, lead to the breach of Section 2 of the laws. The Jews were also prohibited from associating with both the Reich and the German national flag. For instance, Section 4 of the Nuremberg Laws prohibited any Jewish person from hosting the Reich and/or national flag as well as hosting the colours of the Reich (Ward & Gainty, 2012). The punishments that were to be meted against the Jews who were deemed to have acted in breach of sections 1-4 of the Nuremberg Laws varied in nature, and were provided under Section 5 of the laws. For instance, acting contrary to Section 1 of the laws attracted hard labour as punishment, whereas that who breached Section 2 of the said laws was liable for imprisonment or hard labour (Ward & Gainty, 2012). Similarly, Section 5 of the laws provided that whoever (i. e. any Jew) was found to have acted contrary to the provisions of Sections 3 and 4 of the laws would be liable for imprisonment for a period of not more than 1 year, and with a fine or with one of the penalties provided thereof (Ward & Gainty, 2012). In conclusion therefore, the Nuremberg Laws, when viewed from legal and moral perspectives, appear to be both illegal (especially in the context of international humanitarian law) and immoral, as they aimed at legalizing open discrimination against the Jews and denying members of the Jewish community the right to freedom of association and expression of free will. In addition, the supposed punishments for acting in breach of the various Sections of the laws were controversial, and so depended on the mood and attitude of whoever was presiding over as the ‘judge. ’ For instance, Section 5(3) of the laws fell short of defining what constituted a fine as a punishment for acting in breach of Sections 3 and 4 of the laws. The implication thereof is that a ‘judge’ may sometimes impose a fine that is not commensurate with the offence committed. References Hoss, R. (2013). â€Å"Memoirs. † Swerdloff, Howard. The World since 1924. Boston, New York: Bedford/St. Martin’s Press. Stimson, H. L. (2013). The Decision to Use the Atomic Bomb. Swerdloff, Howard. The World since 1914. Boston, New York: Bedford/St. Martin’s Press. Ward. D. W. , & Gainty, D. (2011). Sources of World Societies vol II, since 1450. Second Edition (pp. 1-512). Boston, New York: Bedford/St. Martin’s Press. Ward. D. W. , & Gainty, D. (2012). The Nuremberg Laws: The Centerpiece of Nazi Racial Legislation (331-333), in Sources of World Societies. Volume 2: Since 1450 (2nd Ed). Boston: Bedford.

Wednesday, October 23, 2019

Why trains are the best way to travel Essay

WHEN you travel long term you have plenty of time to ponder the big questions. Maybe that’s why philosophy and travel go so well together. You finally have the time to really think about what the hell Confucius and Plato were trying to get at†¦ Maybe that’s why I also love to travel by rail. Above all other forms of long distance transport, trains are my favourite. I’m comfortably sitting, watching a frozen landscape of farmland, forests and tiny villages fly by my window. Drifts of snow rise and fall like endless frozen waves as skeletal trees scratch at the sky across the distance, disappearing over the horizon, as the sun sets in a radiant arc of crimson fire. The world is bare, open and, above all else, interesting and full of wonder. This is what should make train rides important to travellers. Modern conveniences like email, smartphones and supermarkets have made life more efficient than ever before but in doing so something’s been lost. Don’t get me wrong, 2013 is the best time to be alive (ever!), but I do think we all could learn to appreciate ‘the journey’ a little more than we do. In modern life the journey has taken a definitive backseat to the destination. I put long distance train travel in roughly the same category as calligraphy, wax seals, orchestras and Shakespearean English. There may be more efficient, easier and faster ways to accomplish writing, making music or talking but the ‘romance of the journey’ makes these endeavours both interesting and valuable. The difference is not taking the journey for an inconvenience that’s in the way of getting somewhere, but rather in enjoying the journey for what it is. Flying is obviously more efficient in regards to time, but it lacks in journey aesthetics. Taking a commercial flight really doesn’t allow for much appreciation for a country’s’ aesthetics (unless you count Virgin’s flight attendants) . Another downside to flying is that planes are cramped, much like being a sardine in a can (only with less vegetable oil). There’s also the fact that you’re hurtling through the open sky at 800km/h in a hulking 500 tonne machine made of metal and plastic – maybe you can tell that I’m not a fan of flying. What about buses? Buses unfortunately are a necessary evil in the same way that McDonalds is a necessary evil at 3am on a Sunday morning. Buses, while often cheap offer neither efficiency or the journey experience and come a very distant third choice. Railroads are quite often cut through remote  wilderness far from highways and roads, giving you a sense of remoteness that’s hard to match with other forms of transportation, perfect for moments of quiet contemplation and reflection and often amplified by the beautiful scenery. There’s also the comfort factor to consider. If you’re the butt of beanstalk jokes, journeying by rail allows for more leg and shoulder room than a bus and a flight combined.

Tuesday, October 22, 2019

Network Programming with Sockets Essays

Network Programming with Sockets Essays Network Programming with Sockets Essay 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 w ithin 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 Socket s 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 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 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. 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 mind, 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 a re some facts: if you send 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, fi ve seconds, hell re-transmit 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 hardware (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 Lay er 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 b ear 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. ) s truct sockaddr_in { short 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 re quires careful examination 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) an d long (four bytes). These 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 byt e order, your program will 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 *);their_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 ( cs. umn. edu/~bentlema/unix/has other 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 ( 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 (TFTP) (ftp://nic. ddn. mi l/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. In 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 Dateien/Manualz/not ad r amming; Using Internet Sockets/net. htmlBeejs Guide to Network Programming Using Internet Sockets Version 1. 5. 4 (17-May-1998) [ 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? gethostn ame()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 want to communicate with another pro gram 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 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 mind, 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 send 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-transmit the packet until he finally gets an ACK. This acknowledgment procedure is very important when implementing SOCK_DGRAM applications. Low level Nonsense and Network TheorySince 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 (encapsul ated) 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 pres ent 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 hardware (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 th e 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 { short 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 si n_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 examination 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 t alk 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). These 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 net work 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 will 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 *);their_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.