Socket Programming

31
1 C h a p t e r 1 SOCKET PROGRAMMING B.Vijayalakshmi AP/CSE, RIT

Transcript of Socket Programming

Socket

SOCKET PROGRAMMING

B.VijayalakshmiAP/CSE, RIT#Chapter 1SocketWhat is a socket?The point where a local application process attaches to the networkAn interface between an application and the networkAn application creates the socket The interface defines operations forCreating a socketAttaching a socket to the networkSending and receiving messages through the socketClosing the socket

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer23What is a socket?An interface between application and networkThe application creates a socketThe socket type dictates the style of communicationreliable vs. best effortconnection-oriented vs. connectionlessOnce configured the application canpass data to the socket for network transmissionreceive data from the socket (transmitted through the network by some other host)#Chapter 1SocketSocket FamilyPF_INET denotes the Internet family PF_UNIX denotes the Unix pipe facility PF_PACKET denotes direct access to the network interface (i.e., it bypasses the TCP/IP protocol stack)

Socket TypeSOCK_STREAM is used to denote a byte streamSOCK_DGRAM is an alternative that denotes a message oriented service, such as that provided by UDP

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer45Two essential types of socketsSOCK_STREAMa.k.a. TCPreliable deliveryin-order guaranteedconnection-orientedbidirectionalSOCK_DGRAMa.k.a. UDPunreliable deliveryno order guaranteesno notion of connection app indicates dest. for each packetcan send or receiveAppsocket321Dest.Appsocket321D1D3D2#Chapter 1DescriptorreferencesApplicationsUDP socketsTCP socketsSockets bound to portsTCP portsUDP ports65535126553512UDPTCPIPSockets#Chapter 17Ports

Port 0Port 1Port 65535Each host has 65,536 portsSome ports are reserved for specific apps20,21: FTP23: Telnet80: HTTP

A socket provides an interface to send data to/from the network through a port#Chapter 18Addresses, Ports and SocketsLike apartments and mailboxesYou are the applicationYour apartment building address is the addressYour mailbox is the portThe post-office is the networkThe socket is the key that gives you access to the right mailbox (one difference: assume outgoing mail is placed by you in your mailbox)

#Chapter 1Sockets - Procedures#Chapter 1Stream(e.g. TCP)Datagram(e.g. UDP)ServerClientServerClientsynchronizationpointCS556 - Distributed SystemsTutorial by Eleftherios Kosmas16close()close()close()close()recvfrom()sendto()recv()send()sendto()recvfrom()send()recv()connect()accept()listen()bind()bind()bind()socket()socket()socket()socket()Client - Server Communication - Unix#Chapter 111Socket Creation in C: socketint s = socket(domain, type, protocol);s: socket descriptor, an integer (like a file-handle)domain: integer, communication domaine.g., PF_INET (IPv4 protocol) typically usedtype: communication typeSOCK_STREAM: reliable, 2-way, connection-based serviceSOCK_DGRAM: unreliable, connectionless,other values: need root permission, rarely used, or obsoleteprotocol: specifies protocol (see file /etc/protocols for a list of options) - usually set to 0#Chapter 1Creating a Socketint sockfd = socket(address_family, type, protocol);

The socket number returned is the socket descriptor for the newly created socket

int sockfd = socket (PF_INET, SOCK_STREAM, 0);int sockfd = socket (PF_INET, SOCK_DGRAM, 0);

The combination of PF_INET and SOCK_STREAM implies TCP

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer12 Socket API defines a generic data type for addresses:struct sockaddr {unsigned short sa_family; /* Address family (e.g. AF_INET) */char sa_data[14];/* Family-specific address information */} Particular form of the sockaddr usedstruct in_addr {unsigned long s_addr;}struct sockaddr_in {for TCP/IP addresses:/* Internet address (32 bits) */unsigned shortunsigned shortstruct in_addrsin_family;sin_port;sin_addr;/* Internet protocol (AF_INET) *//* Address port (16 bits) *//* Internet address (32 bits) *//* Not used */char sin_zero[8];}) Important: sockaddr_in can be casted to a sockaddrSpecifying Addresses#Chapter 1Client-Serve Model with TCPServerPassive openPrepares to accept connection, does not actually establish a connection

Server invokesint bind (int socket, struct sockaddr *address, int addr_len)int listen (int socket, int backlog)int accept (int socket, struct sockaddr *address,int *addr_len)

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer14Client-Serve Model with TCPBindBinds the newly created socket to the specified address i.e. the network address of the local participant (the server)Address is a data structure which combines IP and port

ListenDefines how many connections can be pending on the specified socket

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer15Client-Serve Model with TCPAcceptCarries out the passive openBlocking operation Does not return until a remote participant has established a connectionWhen it does, it returns a new socket that corresponds to the new established connection and the address argument contains the remote participants address

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer1617The bind functionassociates and (can exclusively) reserves a port for use by the socketint status = bind(sockid, &addrport, size);status: error status, = -1 if bind failedsockid: integer, socket descriptoraddrport: struct sockaddr, the (IP) address and port of the machine (address usually set to INADDR_ANY chooses a local address)size: the size (in bytes) of the addrport structurebind can be skipped for both types of sockets. When and why?

#Chapter 118Connection Setup (SOCK_STREAM) Recall: no connection setup for SOCK_DGRAMA connection occurs between two kinds of participantspassive: waits for an active participant to request connectionactive: initiates connection request to passive sideOnce connection is established, passive and active participants are similarboth can send & receive dataeither can terminate the connection#Chapter 119Connection setup contdPassive participantstep 1: listen (for incoming requests)step 3: accept (a request)step 4: data transferThe accepted connection is on a new socketThe old socket continues to listen for other active participantsWhy?Active participant

step 2: request & establish connection

step 4: data transferPassive Participant

l-socka-sock-1a-sock-2Active 1socketActive 2socket#Chapter 120Connection setup: listen &acceptCalled by passive participantint status = listen(sock, queuelen);status: 0 if listening, -1 if error sock: integer, socket descriptorqueuelen: integer, # of active participants that can wait for a connectionlisten is non-blocking: returns immediatelyint s = accept(sock, &name, &namelen);s: integer, the new socket (used for data-transfer)sock: integer, the orig. socket (being listened on)name: struct sockaddr, address of the active participantnamelen: sizeof(name): value/result parametermust be set appropriately before calladjusted by OS upon returnaccept is blocking: waits for connection before returning #Chapter 1Client-Serve Model with TCPClientApplication performs active openIt says who it wants to communicate with

Client invokesint connect (int socket, struct sockaddr *address,int addr_len)

ConnectDoes not return until TCP has successfully established a connection at which application is free to begin sending dataAddress contains remote machines address

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer2122connect callint status = connect(sock, &name, namelen);status: 0 if successful connect, -1 otherwisesock: integer, socket to be used in connectionname: struct sockaddr: address of passive participantnamelen: integer, sizeof(name)connect is blocking#Chapter 1Client-Serve Model with TCPOnce a connection is established, the application process invokes two operation

int send (int socket, char *msg, int msg_len, int flags)

int recv (int socket, char *buff, int buff_len, int flags)

#Chapter 1The University of Adelaide, School of Computer Science21 December 2014Chapter 2 Instructions: Language of the Computer2324Sending / Receiving Data With a connection (SOCK_STREAM):int count = send(sock, &buf, len, flags);count: # bytes transmitted (-1 if error)buf: char[], buffer to be transmittedlen: integer, length of buffer (in bytes) to transmitflags: integer, special options, usually just 0int count = recv(sock, &buf, len, flags);count: # bytes received (-1 if error)buf: void[], stores received byteslen: # bytes receivedflags: integer, special options, usually just 0Calls are blocking [returns only after data is sent (to socket buf) / received]#Chapter 125Sending / Receiving Data (contd) Without a connection (SOCK_DGRAM):int count = sendto(sock, &buf, len, flags, &addr, addrlen);count, sock, buf, len, flags: same as sendaddr: struct sockaddr, address of the destinationaddrlen: sizeof(addr)int count = recvfrom(sock, &buf, len, flags, &addr,&addrlen);count, sock, buf, len, flags: same as recvname: struct sockaddr, address of the sourcenamelen: sizeof(name): value/result parameterCalls are blocking [returns only after data is sent (to socket buf) / received]#Chapter 126closeWhen finished using a socket, the socket should be closed:status = close(s);status: 0 if successful, -1 if errors: the file descriptor (socket being closed)Closing a socketcloses a connection (for SOCK_STREAM)frees up the port used by the socket

#Chapter 1Header Files#include This header file contains definitions of a number of data types used in system calls. These types are used in the next two include files.#include The header file socket.h includes a number of definitions of structures needed for sockets. #include The header file netinet/in.h contains constants and structures needed for internet domain addresses.

#Chapter 1Example Application: Server#include#include#include#include#include#include#include#includeint main(){ int sid,bd,lis,acptd,rd,sd; struct sockaddr_in sin; char buf[10]; socklen_t len; sid=socket(PF_INET,SOCK_STREAM,0); if(sid == -1) {

printf("\n Error in creating socket \n"); exit(-1); } printf("\n The socket is created successfully"); memset(&sin,0,sizeof(sin)); sin.sin_family=AF_INET; sin.sin_port=htons(5110); sin.sin_addr.s_addr=htonl(INADDR_ANY); bd=bind(sid,(struct sockaddr*)&sin,sizeof(sin)); if(bd < 0) { printf("\n Binding failed \n"); exit(-1); } printf("\n Binding Completed");

#Chapter 1Example Application: Serverlis=listen(sid,5); if(lis < 0) { printf("\n Error in listening \n"); exit(-1); } printf("\n Listening is completed"); len=sizeof(sin); acptd=accept(sid,(struct sockaddr*)&sin,&len); if(accept < 0) { printf("\n Error in Accepting \n"); exit(-1); } printf("\n Client is Accepted \n"); do {

rd=read(acptd,buf,10); if(rd < 0) { printf("\n Error in receiving the date from the client \n"); exit(-1); } printf(" Message received from client: %s \n",buf); sd=send(acptd,buf,10,0); if(sd < 0) { printf("\n Error in sending the data to the client \n"); exit(-1); } }while(strcasecmp(buf,"END")!=0); close(sid);}#Chapter 1Example Application: Client#include#include#include#include#include#include#include#includeint main(){ int sid,con,sd,rd; struct sockaddr_in sin; char buf[10];sid=socket(PF_INET,SOCK_STREAM,0); if(sid == -1) { printf("\n Error in creating the socket \n"); exit(-1); } printf("\n Socket created successfully"); memset(&sin,0,sizeof(sin)); sin.sin_family=AF_INET; sin.sin_port=htons(5110); sin.sin_addr.s_addr=htonl(INADDR_ANY);

#Chapter 1Example Application: Clientcon=connect(sid,(struct sockaddr*)&sin,sizeof(sin)); if(con < 0) { printf("\n The connection established falied \n"); exit(-1); } printf("\n Connection established successfully \n"); do { printf(" Enter the string: "); scanf("%s",buf); sd=send(sid,buf,10,0); if(sd < 0) { printf("\n Error in sending the data to the server \n"); exit(-1); } rd=read(sid,buf,10); if(rd < 0) { printf("\n Error in reading the data send by the server \n"); exit(-1); } printf(" The content received from sender is: %s \n",buf); }while(strcasecmp(buf,"END")!=0);

shutdown(sid,2); close(sid);}#Chapter 1