Sie sind auf Seite 1von 31

Chapter 1

SOCKET PROGRAMMING
B.Vijayalakshmi
AP/CSE, RIT

What is a socket?

Chapter 1

Socket
The point where a local application process attaches
to the network
An interface between an application and the network
An application creates the socket

The interface defines operations for

Creating a socket
Attaching a socket to the network
Sending and receiving messages through the socket
Closing the socket

Chapter 1

What is a socket?

An interface between application and


network

The application creates a socket


The socket type dictates the style of
communication

reliable vs. best effort


connection-oriented vs. connectionless

Once configured the application can

pass data to the socket for network


transmission
receive data from the socket (transmitted
through the network by some other host)
3

Socket Family

Chapter 1

Socket
PF_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 Type

SOCK_STREAM is used to denote a byte stream


SOCK_DGRAM is an alternative that denotes a
message oriented service, such as that provided by
UDP

Chapter 1

Two essential types of sockets

SOCK_STREAM
a.k.a. TCP
reliable delivery
in-order guaranteed
connection-oriented
bidirectional

App
3 2
1

SOCK_DGRAM
a.k.a. UDP
unreliable delivery
no order guarantees
no notion of connection
app indicates dest. for each
packet
can send or receive
D1

App

socket

Dest.
3 2
1

D2

socket
D3

Chapter 1

Socket
Descriptor
references

Applications

UDP sockets

TCP sockets

Sockets bound to ports


TCP ports

65535

65535

UDP ports

UDP

TCP
IP

Chapter 1

Ports

Each host has


65,536 ports
Some ports are
reserved for specific
apps

20,21: FTP
23: Telnet
80: HTTP

Port 0
Port 1

Port 65535

A socket provides an interface to send data


to/from the network through a port

Chapter 1

Addresses, Ports and Sockets

Like apartments and mailboxes

You are the application


Your apartment building address is the address
Your mailbox is the port
The post-office is the network
The socket is the key that gives you access to the right mailbox
(one difference: assume outgoing mail is placed by you in your
mailbox)

- Procedures

Chapter 1

Sockets

Server

Unix

socket()

(e.g.
TCP)

(e.g. UDP)

Client

Server

socket()

socket()

socket()

bind()

bind()

bind()

Chapter 1

Client
Server
Communication
Stream
Datagram

Client

listen()
accept()

synchronization
point

connect()

recv()

send()

recvfrom()

sendto()

send()

recv()

sendto()

recvfrom()

close()

close()

close()

close()

CS556 - Distributed

Tutorial by Eleftherios Kosmas

16

10

int s = socket(domain, type, protocol);

s: socket descriptor, an integer (like a filehandle)


domain: integer, communication domain

e.g., PF_INET (IPv4 protocol) typically used

type: communication type

Chapter 1

Socket Creation in C: socket

SOCK_STREAM: reliable, 2-way, connection-based


service
SOCK_DGRAM: unreliable, connectionless,
other values: need root permission, rarely used, or
obsolete

protocol: specifies protocol (see file


/etc/protocols for a list of options) - usually set
to 0
11 11

Chapter 1

Creating a Socket
int 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

12

Chapter 1

Specifying
Addresses
Socket API defines a generic data type for addresses:
struct sockaddr {
unsigned short sa_family; /* Address family (e.g.
char
sa_data[14];
/* Family-specific address information
AF_INET)
*/
}

*/

Particular form of the


sockaddr used

struct in_addr {
unsigned long s_addr;
}
unsigned
short
sin_family;
struct
sockaddr_in
{
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];

for TCP/IP addresses:


/* Internet address (32 bits)
*/
/* Internet protocol (AF_INET) */

/* Address port (16 bits) */


/* Internet address (32 bits) */
/* Not used */

) Important: sockaddr_in can be casted to a


13

Chapter 1

Client-Serve Model with TCP


Server

Passive open
Prepares to accept connection, does not actually establish a
connection

Server invokes
int 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)

14

Chapter 1

Client-Serve Model with TCP


Bind

Binds 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

Listen

Defines how many connections can be pending on the specified


socket

15

Chapter 1

Client-Serve Model with TCP


Accept

Carries out the passive open


Blocking operation

Does not return until a remote participant has established a


connection

When it does, it returns a new socket that corresponds to the


new established connection and the address argument
contains the remote participants address

16

Chapter 1

The bind function

associates and (can exclusively) reserves a port for use


by the socket
int status = bind(sockid, &addrport, size);

status: error status, = -1 if bind failed


sockid: integer, socket descriptor
addrport: 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 structure

bind can be skipped for both types of sockets. When


and why?

17 17

Chapter 1

Connection Setup (SOCK_STREAM)

Recall: no connection setup for SOCK_DGRAM


A connection occurs between two kinds of participants

passive: waits for an active participant to request connection


active: initiates connection request to passive side

Once connection is established, passive and active


participants are similar

both can send & receive data


either can terminate the connection

18 18

Chapter 1

Connection setup contd

Passive participant

step 1: listen (for


incoming requests)
step 3: accept (a
request)
step 4: data transfer

The accepted
connection is on a new
socket
The old socket
continues to listen for
other active participants
Why?

Active participant

step 2: request &


establish connection

step 4: data transfer


Passive Participant

a-sock-1

socket

Active 1

l-sock

a-sock-2

socket

Active 2
19 19

Called by passive participant


int status = listen(sock, queuelen);

Chapter 1

Connection setup: listen &accept


status: 0 if listening, -1 if error
sock: integer, socket descriptor
queuelen: integer, # of active participants that can wait for a
connection
listen is non-blocking: returns immediately

int 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 participant
namelen: sizeof(name): value/result parameter

must be set appropriately before call


adjusted by OS upon return

accept is blocking: waits for connection before returning

20 20

Chapter 1

Client-Serve Model with TCP


Client

Application performs active open


It says who it wants to communicate with

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

Connect

Does not return until TCP has successfully established a


connection at which application is free to begin sending data
Address contains remote machines address

21

Chapter 1

connect call

int status = connect(sock, &name,


namelen);

status: 0 if successful connect, -1 otherwise


sock: integer, socket to be used in connection
name: struct sockaddr: address of passive
participant
namelen: integer, sizeof(name)

connect is blocking

22 22

Chapter 1

Client-Serve Model with TCP


Once 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)

23

With a connection (SOCK_STREAM):

int count = send(sock, &buf, len, flags);

count: # bytes transmitted (-1 if error)


buf: char[], buffer to be transmitted
len: integer, length of buffer (in bytes) to transmit
flags: integer, special options, usually just 0

int count = recv(sock, &buf, len, flags);

Chapter 1

Sending / Receiving Data

count: # bytes received (-1 if error)


buf: void[], stores received bytes
len: # bytes received
flags: integer, special options, usually just 0

Calls are blocking [returns only after data is


sent (to socket buf) / received]
24 24

Without a connection (SOCK_DGRAM):

int count = sendto(sock, &buf, len, flags, &addr,


addrlen);

count, sock, buf, len, flags: same as send


addr: struct sockaddr, address of the destination
addrlen: sizeof(addr)

int count = recvfrom(sock, &buf, len, flags,


&addr,&addrlen);

count, sock, buf, len, flags: same as recv


name: struct sockaddr, address of the source
namelen: sizeof(name): value/result parameter
Calls are blocking [returns only after data is sent (to socket
buf) / received]
25 25

Chapter 1

Sending / Receiving Data (contd)

Chapter 1

close

When finished using a socket, the socket


should be closed:
status = close(s);

status: 0 if successful, -1 if error


s: the file descriptor (socket being closed)

Closing a socket

closes a connection (for SOCK_STREAM)


frees up the port used by the socket

26 26

Chapter 1

Header Files
#include <sys/types.h>
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 <sys/socket.h>
The header file socket.h includes a number of definitions
of structures needed for sockets.
#include <netinet/in.h>
The header file netinet/in.h contains constants and
structures needed for internet domain addresses.

27

Chapter 1

Example Application: Server


#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int 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");

28

Chapter 1

Example Application: Server


lis=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);

29

#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<stdlib.h>
int 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);

Chapter 1

Example Application: Client

30

con=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)
{

Chapter 1

Example Application: Client

31

Das könnte Ihnen auch gefallen