0% found this document useful (0 votes)
275 views70 pages

NP Sockets

The document discusses sockets programming and the Berkeley sockets API. It provides an overview of sockets, describing them as abstract representations of communication endpoints that work similarly to files. It covers the key socket functions like socket(), bind(), connect(), and others. It also discusses the necessary data types, structures like sockaddr_in, and byte order transformation functions needed for sockets programming.

Uploaded by

om18sahu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
275 views70 pages

NP Sockets

The document discusses sockets programming and the Berkeley sockets API. It provides an overview of sockets, describing them as abstract representations of communication endpoints that work similarly to files. It covers the key socket functions like socket(), bind(), connect(), and others. It also discusses the necessary data types, structures like sockaddr_in, and byte order transformation functions needed for sockets programming.

Uploaded by

om18sahu
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 70

Sockets Programming

Netprog: Sockets API


1
Network Application
Programming Interface (API)
• The services provided (often by the operating
system) that provide the interface between
application and protocol software.

Application

Network API

Protocol A Protocol B Protocol C

Netprog: Sockets API


2
Network API wish list
• Generic Programming Interface.
• Support for message oriented and
connection oriented communication.
• Work with existing I/O services (when
this makes sense).
• Operating System independence.
• Presentation layer services
Netprog: Sockets API
3
Generic Programming
Interface
• Support multiple communication
protocol suites (families).
• Address (endpoint) representation
independence.
• Provide special services for Client and
Server?

Netprog: Sockets API


4
TCP/IP
• TCP/IP does not include an API
definition.
• There are a variety of APIs for use with
TCP/IP:
– Sockets
– Winsock
– MacTCP

Netprog: Sockets API


5
Functions needed:
• Specify local and remote
communication endpoints
• Initiate a connection
• Wait for incoming connection
• Send and receive data
• Terminate a connection gracefully
• Error handling
Netprog: Sockets API
6
Berkeley Sockets
• Generic:
– support for multiple protocol families.
– address representation independence
• Uses existing I/O programming
interface as much as possible.

Netprog: Sockets API


7
Socket
• A socket is an abstract representation
of a communication endpoint.
• Sockets work with Unix I/O services
just like files, pipes & FIFOs.
• Sockets (obviously) have special
needs:
– establishing a connection
– specifying communication endpoint
addresses
Netprog: Sockets API
8
Unix Descriptor Table
Descriptor Table
Data structure for file 0
0
1
2 Data structure for file 1

3
4 Data structure for file 2

Netprog: Sockets API


9
Socket Descriptor Data
Structure
Descriptor Table
Family: PF_INET
0
Service: SOCK_STREAM
1 Local IP: 111.22.3.4
2 Remote IP: 123.45.6.78
Local Port: 2249
3 Remote Port: 3726
4

Netprog: Sockets API


10
Creating a Socket
int socket(int family,int type,int proto);

• family specifies the protocol family


(PF_INET for TCP/IP).
• type specifies the type of service
(SOCK_STREAM, SOCK_DGRAM).
• protocol specifies the specific protocol
(usually 0, which means the default).
Netprog: Sockets API
11
socket()
• The socket() system call returns a
socket descriptor (small integer) or -1
on error.

• socket() allocates resources needed


for a communication endpoint - but it
does not deal with endpoint addressing.

Netprog: Sockets API


12
Specifying an Endpoint
Address
• Remember that the sockets API is
generic.
• There must be a generic way to specify
endpoint addresses.
• TCP/IP requires an IP address and a
port number for each endpoint address.
• Other protocol suites (families) may use
other schemes.
Netprog: Sockets API
13
Necessary Background Information:
POSIX data types
int8_t signed 8bit int
uint8_t unsigned 8 bit int
int16_t signed 16 bit int
uint16_t unsigned 16 bit int
int32_t signed 32 bit int
uint32_t unsigned 32 bit int

u_char, u_short, u_int, u_long

Netprog: Sockets API


14
More POSIX data types
sa_family_t address family
socklen_t length of struct
in_addr_t IPv4 address
in_port_t IP port number

Netprog: Sockets API


15
Overview of Socket Interface
• Client-server model
– local system (a client)
– remote system (a server)
• These two machines need to communicate with one another
• socket provide a standard interface, API, for programmer to
write client-server applications
– declarations
– definitions
– procedures
• There are several APIs we only concentrate
socket interface
– socket interface
– TLI (transport level interface)
– RPC (remote procedure call)

Netprog: Sockets API


16
Data types and Data structures
• 3 data types commonly used
– u_char unsigned 8-bit character
– u_short unsigned 16-bit integer
– u_long unsigned 32-bit integer
• Internet Address
– IPv4 define a structure call in_addr
– 32 bit binary number
– struct in_addr
{
u_long s_addr;
} Netprog: Sockets API
17
Internet Socket Address Structure
• TCP/IP protocol suite need a structure called socket address to
holds IP address, port number, protocol type and protocol family
• A socket is an abstract representation of a communication
endpoint.
– acts a an end-port
– two processes need a socket at each end to communicate with
each other
• Sockets work with Unix I/O services just like files, pipes &
FIFOs.
• Socket structure start from socket
– family address
– type
– protocol
– local socket address
– remote socket addressNetprog: Sockets API
18
Internet socket address
structure
• Struct sockaddr_in
{
u_char sin_len;
u_short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
}

sin_len sin_family sin_port sin_addr sin_zero


Netprog: Sockets API
19
Socket structure
• Socket structure (it is a bigger picture!!)
– family
– type
– protocol
– local socket address
– remote socket address

Family Type Protocol

local

sin_len sin_family sin_port sin_addr sin_zero

remote

sin_len sin_family sin_port sin_addr sin_zero


Netprog: Sockets API
20
Socket types
• three types
– stream socket
• connection-oriented protcol such as TCP
• TCP uses a pair of stream sockets to connect one
application program to anther over the Internet
– datagram socket
• connectionless protocol such as UDP
• UDP uses a pair of datagram sockets to send message
from one applications program to another over the
Internet
– raw socket
• designed for services and application such as ICMP or
OSFP Netprog: Sockets API
21
Socket types

application program
stream datagram
socket socket raw
interface interface socket
interface
TCP UDP

IP

Physical and data link layers

Netprog: Sockets API


22
overview of API functions
• byte order transformation (htons, htonl, ntohs
and ntohl)
• address transformation (inet_aton, inet_ntoa)
• byte manipulation (memset, memcpy,
memcmp)
• get information about remote host
(gethostbyname)
• socket system calls (socket, bind, connect,
listen, accept, sendto, recvfrom, read, write,
close)
Netprog: Sockets API
23
Byte ordering
• two types
– big-endian
• MSB first
– little-endian
• LSB first
• IP address use big-endian
– MSB first
• To create portability in applications program, API
provides a set of functions that transforms integers
from a host byte order (big endian or little endian) to
network type order (big endian)
• Four functions are provided
– htons, htonl, ntohs and ntohl
Netprog: Sockets API
24
Byte order transformation
• u_short htons(u_short host_short)
– function host to network short convert 16-bit
integer from host byte order to network byte order
• u_short ntohs(u_short network_short)
– function network to host short convert 16-bit
integer from host byte order to network byte order
• u_long htonl(u_short host_long)
– function host to network long convert 32-bit integer
from host byte order to network byte order
• u_long ntohl(u_short network_long)
– function networkNetprog:
to host long convert 32-bit integer
Sockets API
from network byte order to host byte order 25
Byte order transformation

host byte
16-bit order 32-bit

htons ntons htonl ntohl

network byte
16-bit order 32-bit

Netprog: Sockets API


26
Address transformation
• transform an IP address ASCII dotted decimal format to 32-bit
binary format and vice versa
– int inet_aton(const char *strptr, struct in_addr *addrptr)
• transforms an ASCII string contains 4 segment separated by dots to a
32-bit binary address in network byte order
– char *inet_nota(struct in_addr inaddr)
• transforms a 32bit binary address in network byte order to an ASCII
string with 4 segments separated by dots.

32 bit binary address

inet_ntoa inet_aton

dotted decimal address

Netprog: Sockets API


27
byte manipulation
• In network programming, we often need to initialize a
field, copy the contents of one field to another, or
compare the contents of two fields
• memset
– void *memset(void *dest, int chr,int len);
– e.g memset(&x, 0, sizeof(x));
• memcpy
– void *memcpy(void *dest, const void *src, int len);
– e.g. memcpy(&x, &y, sizeof(x));
• memcmp
– int memcmp (const void *first, const void *second, int len);
– e.g. memcmp(&x, &y, 10);
Netprog: Sockets API
28
information about remote host
• In many instances, it is necessary to get
information about a remote host
– struct hostent *gethostbyname(const char
*hostname);
– call to the DNS, this function accepts the domain
name of the host and returns structured
information called hostent, a pointer to the hostent
structure
– struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
Netprog: Sockets API
int h_length;
char **h_addr_list;
29
Socket System Calls

Netprog: Sockets API


30
Socket System Calls
• previous sections
– utilities for client-server program
• byte order transformation (htons, htonl, ntohs and ntohl)
• address transformation (inet_aton, inet_ntoa)
• byte manipulation (memset, memcpy, memcmp)
• get information about remote host (gethostbyname)
• this section
– Socket system calls used by application program
to communicate with another application program
– socket
– bind, connect,
– listen, accept,
– sendto, recvfrom Netprog: Sockets API
31
el
Generic socket addresses   ke rn
y
d b
s e
struct sockaddr { U
uint8_t sa_len;
sa_family_t sa_family;
char sa_data[14];
};

• sa_family specifies the address type.


• sa_data specifies the address value.
Netprog: Sockets API
32
sockaddr
• An address that will allow me to use
sockets to communicate with my kids.
• address type AF_DAVESKIDS
• address values:
Andrea 1 Mom 5
Jeff 2 Dad 6
Robert 3 Dog 7
Emily 4
Netprog: Sockets API
33
AF_DAVESKIDS
• Initializing a sockaddr structure to point
to Robert:

struct sockaddr robster;

robster.sa_family = AF_DAVESKIDS;
robster.sa_data[0] = 3;

Netprog: Sockets API


34
AF_INET
• For AF_DAVESKIDS we only needed 1
byte to specify the address.
l y !
  on
• For AF_INET we need: v4
IP
– 16 bit port number
– 32 bit IP address

Netprog: Sockets API


35
struct sockaddr_in (IPv4)
struct sockaddr_in {
uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
A special kind of sockaddr structure
Netprog: Sockets API
36
struct in_addr
struct in_addr {
in_addr_t s_addr;
};

in_addr just provides a name for the ‘C’ type


associated with IP addresses.

Netprog: Sockets API


37
Network Byte Order
• All values stored in a sockaddr_in
must be in network byte order.
– sin_port a TCP/IP port number.
– sin_addr an IP address.

Netprog: Sockets API


38
Network Byte Order Functions
‘h’ : host byte order ‘n’ : network byte order
‘s’ : short (16bit) ‘l’ : long (32bit)

uint16_t htons(uint16_t);
uint16_t ntohs(uint_16_t);

uint32_t htonl(uint32_t);
uint32_t ntohl(uint32_t);

Netprog: Sockets API


39
TCP/IP Addresses
• We don’t need to deal with sockaddr
structures since we will only deal with a
real protocol family.
• We can use sockaddr_in structures.

BUT: The C functions that make up the


sockets API expect structures of type
sockaddr.
Netprog: Sockets API
40
sockaddr sockaddr_in
sa_len sin_len
sa_family AF_INET
sin_port

sin_addr
sa_data

sin_zero

Netprog: Sockets API


41
Assigning an address to a
socket
• The bind() system call is used to assign
an address to an existing socket.

int bind( int sockfd,


const struct sockaddr *myaddr,
const! int addrlen);

• bind returns 0 if successful or -1 on error.

Netprog: Sockets API


42
bind()
• calling bind() assigns the address
specified by the sockaddr structure to
the socket descriptor.
• You can give bind() a sockaddr_in
structure:
bind( mysock,
(struct sockaddr*) &myaddr,
sizeof(myaddr) );

Netprog: Sockets API


43
bind() Example
int mysock,err;
struct sockaddr_in myaddr;

mysock = socket(PF_INET,SOCK_STREAM,0);
myaddr.sin_family = AF_INET;
myaddr.sin_port = htons( portnum );
myaddr.sin_addr = htonl( ipaddress);

err=bind(mysock, (sockaddr *) &myaddr,


sizeof(myaddr));

Netprog: Sockets API


44
Uses for bind()
• There are a number of uses for bind():
– Server would like to bind to a well known
address (port number).

– Client can bind to a specific port.

– Client can ask the O.S. to assign any


available port number.
Netprog: Sockets API
45
Port - who cares ?
• Clients typically don’t care what port
they are assigned.
• When you call bind you can tell it to
assign you any available port:

myaddr.port = htons(0);

Netprog: Sockets API


46
What is my IP address ?
• How can you find out what your IP address is
so you can tell bind() ?
• There is no realistic way for you to know the
right IP address to give bind() - what if the
computer has multiple network interfaces?

• specify the IP address as: INADDR_ANY,


this tells the OS to take care of things.

Netprog: Sockets API


47
IPv4 Address Conversion
int inet_aton( char *, struct in_addr *);

Convert ASCII dotted-decimal IP address to


network byte order 32 bit value. Returns 1
on success, 0 on failure.

char *inet_ntoa(struct in_addr);

Convert network byte ordered value to


ASCII dotted-decimal (a string).
Netprog: Sockets API
48
Other socket system calls
• General Use • Connection-oriented
– read() (TCP)
– write() – connect()
– close() – listen()
– accept()

• Connectionless (UDP)
– send()
– recv()
Netprog: Sockets API
49
Threads
• Threads are lightweight process which share the process
instructions , global variables , open files , signal handlers and
signal dispositions , current working directory and user and
group Ids
• Each thread has its own thread ID , set of Registers, PC and
Stack pointer, stack , errno ,signal mask , priority
• Basic Thread Functions : Creation and Termination
• Int pthread_create(pthread_t *tid,const pthread_attr_t *attr,void
*(*func)(void*), void *arg);
• Int pthread_join(pthread_t tid,void **status); // Wait for a thread
to terminate
• pthread_t pthread_self(void); //Returns thread ID of calling
thread
• Int pthread_detach(pthread_t pid);//We cannot wait for it to
terminate, On its termination all resources are released
• Void pthread_exit(void *status);
• Threads/tcpserv01.c
Netprog: Sockets API
50
Thread Synchronization
• Shared data can be protected using mutex locks provided by
the pthread library
• int pthread_mutex_lock(pthread_mutex_t *mptr);
• int pthread_mutex_unlock(pthread_mutex_t *mptr);
• Threads/example02.c
• Can use condition variables for signalling mechanism
• int pthread_cond_wait(pthread_cond_t *cptr,pthread_mutex_t
*mptr);
• int pthread_cond_signal(pthread_cond_t *cptr);
• Can also use System semaphores from <semaphores.h> See
manual
~syrotiuk/pthreads.cc

Netprog: Sockets API


51
Quiz
1. The structure to define an IPv4 address
is called a _________ and contains a
field called ___________.
• u_long; s_addr
• s_addr; in_addr
• in_addr; s_addr (***)
• in_addr; u_long
Netprog: Sockets API
52
Quiz
2. The ______ socket is used with a
connection-orientation protocol
• stream (***)
• dataram
• raw
• remote

Netprog: Sockets API


53
Quiz
3. The ______ socket is used with a
connectionless protocol
• stream
• datagram(***)
datagram
• raw
• remote

Netprog: Sockets API


54
Quiz
4. To convert a dotted decimal address to
a 32-bit binary address, use the
_______ function
• htons
• htol
• inet_ntoa
• inet_aton (****)
Netprog: Sockets API
55
Quiz
5. To convert a 32-bit integer from
network byte order to host byte order,
use the _______ function
• htons
• ntohs
• htonl
• ntohl (****)
Netprog: Sockets API
56
Quiz
6. The ________ function provide
information about the remote host
• hostent
• hostname
• gethostbyname (****)
• getnameofhost

Netprog: Sockets API


57
Quiz
7. A connectionless process issues the
________ system call to receive, from
the incoming queue, the datagrams
sent by a remote process.
• listen
• receive
• bind
• recvfrom (***)
Netprog: Sockets API
58
Quiz
8. A connection-oriented process issues
the ________ system call to send
datagrams to a remote process.
• sendto
• bind
• accept
• write (***)
Netprog: Sockets API
59
Client/Server TCP Socket
Interaction: Pseudo-code

Netprog: Sockets API


60
Pseudo-code for a simple
server and client
1. create an unnamed 1. create an unnamed
socket socket
2. name the socket 2. name the socket to
3. create a queue for agree with the
hold client requests server choices
4. accept a connection 3. request connection
upon receive a from the server
request from a (upon success, the
client connection is
established)
5. communicate (R/W)
with the client as 4. communicate (W/R)
needed with the server as
needed
6. close any open
sockets when done 5. close any open
sockets when done
Netprog: Sockets API
61
Basic Socket API in C – cont.
The following consists of declaring a structure to hold the name
information, filling out that structure, and then making the bind
call to bind the structure to the formerly unnamed socket.
Int serv_len, result;
struct sockaddr_in serv_addr;

serv_sock_desc=socket(AF_INET, SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
result=inet_aton(“127.0.0.1”, &serv_addr.sin_addr);
if (result==0) {
perror(“inet_aton error”);
exit(0);
}
serv_addr.sin_port=htons(4242);
serv_len=sizeof(serv_addr); Netprog: Sockets API
bind(serv_sock_desc, (struct sockaddr *)&serv_addr, serv_len); 62
Basic Socket API in C – cont.
a socket to a port address
FORMAT: int bind(int serv_sock_desc,(struct sockaddr *)&serv_addr, int
serv_len)
The bind function takes three arguments:
– The socket descriptor returned by an earlier call to socket
– The address of the sockaddr structure holding the name
information
– The length of that name structure
The name information in the sockaddr structure
includes:
– domain (AF_INET)
– internet address of the socket (127.0.0.1)
– port number to be bound to the socket, we have chosen port
number 4242 in theNetprog: Sockets API
lab. session
63
Basic Socket API in C – cont.
Create a queue for client request –server code
– The listen call creates a queue for holding
pending clinet requests.
listen(serv_sock_desc,1);
The two arguments to listen are
– The socket descriptor for the socket being
listened to (serv_sock_dec)
– The queue length desired – arbitrary, we’ll use 1
for our example, but something like 5 would be
more typical

Netprog: Sockets API


64
Basic Socket API in C – cont.
Accept a connection – server code
The default behavior of accept is to block until
a client connects.

int cli_sock_desc, cli_len;


struct sockaddr_in cli_addr;
cli_len = sizeof(cli_addr);
cli_sock_desc = accept(serv_sock_addr,(stuct sockaddr *)
&cli_addr, &cli_len);

Note: accept return a new socket descriptor by using the


existing socket (identified by serv_sock_addr) as a
template for the type. This is reasonable since a server can
connect to multiple clients.
Netprog: Sockets API
65
Basic Socket API in C – cont.
The accept function has three
arguments:
– original socket, serv_sock_addr, to use
a template for the type
– reference to the sockaddr for the new
socket (it receives the address of the
calling client)
– The expected address length (gets reset
to the actual length)
Netprog: Sockets API
66
Basic Socket API in C – cont.

Communicate with the client – server code


Communication can be carried out with read and write calls. For
example, to read a character from the client and write it back,
we might have:

char ch;
read(cli_sock_desc, &ch, 1);
write(cli_sock_desc, &ch, 1);

Note: we use the socket descriptor returned by an earlier accept


call.
Netprog: Sockets API
67
Basic Socket API in C – cont.
Close the socket – server code
This is simply:
close(cli_sock_desc);
close(serv_sock_desc);

Note: If we now look at the client we note that it has


very similar pseudo code except that it has no
listen or accept calls, but does have a need to
make a connection request.
Netprog: Sockets API
68
Basic Socket API in C – cont.
Create an unnamed socket –
client code
This is basically the same as for the
server, with a trivial name change for
the socket descriptor:
int client_sock_desc;
client_sock_desc=socket(AF_INET,SOCK_STREAM,0);

…………… and so on.


Netprog: Sockets API
69
Thanks

Netprog: Sockets API


70

You might also like