New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here


by: Adele Schaden MD


Adele Schaden MD
GPA 3.88


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 7 page Class Notes was uploaded by Adele Schaden MD on Thursday October 29, 2015. The Class Notes belongs to CS 164 at University of California Riverside taught by Staff in Fall. Since its upload, it has received 28 views. For similar materials see /class/231757/cs-164-university-of-california-riverside in ComputerScienence at University of California Riverside.

Similar to CS 164 at UCR

Popular in ComputerScienence




Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 10/29/15
Introduction to Socket Programming Part 11 Code snipet struct sockaddriin myAddressStruct F ill in the address information into myAddressStruct here will be explained in detail shortly connectsocketifileidescriptor struct sockaddr ampmyAddressStruct sizeofmyAddressStruct Now lets discuss how to fill in the sockaddriin structure struct sockaddriin saifamilyit sinifamily AddressProtocol Family unitl67t siniport Port number Network Byte Order struct iniaddr siniaddr A struct for the 32 bit IP Address unsigned char sinizero8 Just ignore this it is just padding struct iniaddr unit327t siaddr 32 bit IP Address Network Byte Order For the saifamily variable sinifamily always use the constant PFilNET or AFilNET Always initialize address structures with bzero or memsetO before filling them in Make sure you use the byte ordering functions when necessary for the port and IP address variables otherwise there will be strange things a happening to your packets Converting between dotted decimal strings and Network Address values Read pgs 70 7 74 Stevens To convert a string dotted decimal 1P4 address to a NETWORK BYTE ORDERED 32 bit value use the functions 0 inetiaddrO 0 inetiatonO To convert a 32 bit NETWORK BYTE ORDERED to a 1P4 dotted decimal string use 0 inetintoaO Read Stevens also for more recent functions which work with both IP4 and 1P6 however in this class we will only be working with 1P4 6 Outline of a TCP Client Read Chapter 4 in Stevens Chem close Step 1 Create a socket int socketint family int type int protocol Read pgs 8688 Stevens Creating a socket is in some ways similar to opening a le This function creates a le descriptor and returns it om the function call You later use this le descriptor for reading writing and using With other socket functions Parameters family AFilNET or PFilNET These are the 1P4 family type SOCKiSTREAM for TCP or SOCKiDGRAM for UDP protocol IPPROTOiTCP for TCP or IPPROTOiUDPforUDP or use0 Step 2 Binding a socket This is unnecessary for a client What hind does is and Will be discussed in detail in the server section is associate a port number to the application If you skip this step With a TCP client a temporary port number is automatically assigned so it is just better to skip this step with the client Step 3 Connecting to a Server Read pgs 89 7 90 Stevens int connectint socketifileidescriptor const struct sockaddr ServerAddress socklenit AddressLength Once you have created a socket and have filled in the address structure of the server you want to connect to the next thing to do is to connect to that server This is done with the connect function listed above This is one of the socket functions which requires an address structure so remember to type cast it to the generic socket structure when passing it to the second argument Connect performs the threeway handshake with the server and returns when the connection is established or an error occurs Once the connection is established you can begin reading and writing to the socket Step 4 Read and Writing to the socket will be discussed shortly Step 5 Closing the socket will be discussed shortly 7 Communicating with send and recv Read pgs 48 7 49 77 7 81 354 7 357 Stevens readwrite These are the same functions you use with files but you can use them with sockets as well However it is extremely important you understand how they work so please read Stevens carefully to get a full understanding Lets start with write int writeint fileidescriptor const void buf sizeit messageilength The return value is the number of bytes written The number of bytes written may be less than the messageilength What this function does is transfer the data from you application to a buffer in the kernel on your machine it does not directly transmit the data over the network This is extremely important to understand otherwise you will end up with many headaches trying to debug your programs TCP is in complete control of sending the data and this is implemented inside the kernel Due to network congestion or errors TCP may not decide to send your data right away even when the function call returns TCP has an elaborate sliding window mechanism which you will learn about in class to control the rate at which data is sent Read pages 4849 7778 in Stevens very carefully Now let us discuss reading from a socket int readint leidescriptor char buffer sizeit bufferilength The value returned is the number of bytes read which may not be bufferilength As with write read only transfers data from a buffer in the kernel to your application you are not directly reading the byte stream from the remote host but rather TCP is in control and buffers the data for your application Read Stevens very carefully especially pages 7778 to understand more how to properly use read recvsend Read pgs 354 7 357 Stevens 8 Shutting down sockets Ater you are finished reading and writing to your socket you most call the close system call on the socket file descriptor just as you do on a normal le descriptor otherwise you waste system resources The close function int closeint filedescriptor The shutdown function You can also shutdown a socket in a partial way which is often used when forking off processes You can shutdown the socket so that it won t send anymore or you could also shutdown the socket so that it won t read anymore as well This function is not so important now but will be discussed in detail later You can look at the man pages for a full description of this function 9 Outline of a TCP Server Read Chapter 4 in Stevens Server closercnem Step 1 Creating a socket Same as in the client Step 2 Binding an address and port number Read pgs 9l 7 93 Stevens int bindint socketi leidescriptor const struct sockaddr LocalAddress socklenit AddressLength We need to associate an IP address and port number to our application A client that wants to connect to our server needs both of these details in order to connect to our server Notice the difference between this function and the connect function of the client The connect function speci es a remote address that the client wants to connect to while here the server is specifying to the bind function a local IP address of one of its Network Interfaces and a local port number MAgain make sure that you cast the structure as a generic address structure in this function You also do not need to nd information about the IP addresses associated with the host you are working on You can specify INNADDRiANY to the address structure and the bind function will use on of the available there may be more than one IP addresses Read Stevens page 92 for more details Step 3 Listen for incoming connections Read pgs 93 7 99 Stevens Binding is like waiting by a specific phone in your house and Listening is waiting for it to ring int listenint socketifileidescriptor int backlog The backlog parameter can be read in Stevens on page 94 It is important in determining how many connections the server will connect with Typical values for backlog are 5 7 10 Step 4 Accepting a connection Read pgs 99 7100 Stevens int accept int socketi leidescriptor struct sockaddr ClientAddress socklenit addrlen accept returns a new socket file descriptor for the purpose of reading and writing to the client The original file descriptor is used usually used for listening for new incoming connections Servers will be discussed in much more detail in a later lab Again make sure you type cast to the generic socket address structure Note that the last parameter is a pointer You are not specifying the length the kernel is and returning the value to your application the same with the ClientAddress After a connection with a client is established the address of the client must be made available to your server otherwise how could you communicate back with the client Therefore the accept function call fills in the address structure and length of the address structure for your use Then accept returns a new file descriptor and it is this file descriptor with which you will read and write to the client 10 Handling Errors When writing your programs you must account for and deal with errors related to any of the socket related functions This means if a socket related function error occurs in your program the program should eXit nicely and display any useful information relating to the error it can give For example your program may call the bind function trying to bind to a port which is not available A value of 71 will be returned from this function indicating a failure so you should catch such an error and display a proper error message Of course there is always the problem of cluttering up your code with error handling statements causing difficulty for someone trying to read the code and understand the ow Therefore some thought in terms of style should be given in dealing with how to incorporate error handling routines Two common practices are as follows A A simple bailout function B Wrapper Functions You are not required to follow either of these practices but if you create your own style in handling errors try to keep it simple yet effective 11 Gathering host information Gathering information about your local host int unamestruct utsname buf struct utsname char sysnameSYSiNMLN char nodename SYSiNMLN char releaseSYSiNMLN char version SYSiNMLN char machineSYSiNMLN char domainnameSYSiNMLN see also 0 gethostname 0 getdomainname Gathering information about a remote host struct hostent gethostbynameconst char name struct hostent char hiname Official name of host char hialiases Alias list int hiaddrtype host address type int hilength length of address char hiaddrilist list of addresses Example struct hostent ptr ptr gethostbynamewwwucredu for int i 0 ptrgth7aliasesi NULL i printf alias sn ptrgth7aliasesi if ptrgth7addrtype AF INET for int i 0 ptrgth7addrilisti NULL i printf Address sn struct iniaddr ptrgth7addrilisti 12 Summary of Functions For specific and uptodate information about each of the following functions please use the online man pages and Steven s Unix Network Programming Vol 1 Socket creation and destruction


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."

Allison Fischer University of Alabama

"I signed up to be an Elite Notetaker with 2 of my sorority sisters this semester. We just posted our notes weekly and were each making over $600 per month. I LOVE StudySoup!"

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.