CS 6390 Advanced Computer NetworksSocket ProgrammingWhat is a socket?Two essential types of socketsSocket Creation in C: socketOur view of the InternetPortsThe bind functionThe struct sockaddrSlide 10Skipping the bindConnection Setup (SOCK_STREAM)Connection setup cont’dConnection setup: listen & acceptconnect callSending / Receiving DataSending / Receiving Data (cont’d)closeAddress and port byte-orderingSolution: Network Byte-OrderingUNIX’s byte-ordering funcsDealing with blocking callsDealing w/ blocking (cont’d)select function callTo be used with select:Other useful functionsRelease of portsFinal Thoughts1CS 6390Advanced Computer NetworksSocket Programming in CSlides by Dan Rubenstein2Socket ProgrammingWhat is a socket?Using socketsTypes (Protocols)Associated functionsIssuesWe will look at using sockets in CSockets in Java have similar logic but much easier to use3What 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)4Two essential types of socketsSOCK_STREAMa.k.a. TCP socketsreliable deliveryin-order guaranteedconnection-orientedbidirectionalSOCK_DGRAMa.k.a. UDP socketsunreliable deliveryno in-order guaranteesno notion of “connection” can send and receiveAppsocket321Dest.Appsocket321D1D3D2Q: why have type SOCK_DGRAM?5Socket 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 0NOTE: socket call does not specify where data will be coming from, nor where it will be going to – it just creates the interface!6Our view of the InternetEach host machine has an IP addressWhat happens when a packet arrives at a host?190.2.4.3167.55.34.13129.55.3.33128.15.44.13128.115.4.32128.11.1.12130.1.1.22134.13.1.2128.110.52.27PortsPort 0Port 1Port 65535Each host has 65,536 portsSome ports are reserved for specific apps20,21: FTP23: Telnet80: HTTPsee RFC 1700 (about 2000 ports are reserved)A socket provides an interface to send data to/from the network through a port8The 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?9The struct sockaddrThe generic:struct sockaddr {u_short sa_family;char sa_data[14];};sa_family specifies which address family is being useddetermines how the remaining 14 bytes are usedThe Internet-specific:struct sockaddr_in {short sin_family;u_short sin_port;struct in_addr sin_addr;char sin_zero[8];};sin_family = AF_INETsin_port: port # (0-65535)sin_addr: IP-addresssin_zero: unusedstruct in_addr { u_long s_addr;};1011Skipping the bindSOCK_DGRAM:if only sending, no need to bind. The OS finds a port each time the socket sends a pktif receiving, need to bind (why?)SOCK_STREAM:destination determined during conn. setupdon’t need to know port sending from (during connection setup, receiving end is informed of port)12Connection 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 “similar”both can send & receive dataeither can terminate the connection13Connection setup cont’dPassive 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 participantstep 2: request & establish connectionstep 4: data transferPassive Participantl-socka-sock-1 a-sock-2Active 1socketActive 2socket14Connection 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 desc. (used for data-transfer)sock: integer, the orig. socket desc. (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 returning15connect 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 blocki ng16Sending / 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]17Sending / Receiving Data (cont’d) Without a connection (SOCK_DGRAM):int count = sendto(sock, &buf, len, flags,
View Full Document