SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
By :- Rishu
 Introduction to Sockets
 A generic Client-Server application
 Programming Client-Server in C
 References
Socket programming
 Why Sockets?
 Used for Interprocess Communication.
 The Client-Server model
 Most Interprocess Communication uses client-server model
 Client & Server are two processes that wants to communicate with each
other
 The Client process connects to the Server process, to make a request for
information/services own by the Server.
 Once the connection is established between Client process and Server
process, they can start sending / receiving information.
 What are Sockets?
 End-point of Interprocess Communication.
 allows communication between two different
processes on the same or different machines
 An interface through which processes can
send / receive information.
Socket
 What exactly creates a Socket?
 <IP address, Port #> tuple
 What makes a connection?
 {Source<IP address, Port #> , Destination <IP address, Port #>} i.e.
source socket – destination socket pair uniquely identifies a connection.
 Example
Server
192.168.0.1
Client
Client
Client
192.168.0.2
192.168.0.2
192.168.0.3
80
1343
1343
5488
 Socket Types
 STREAM – uses TCP which is reliable, stream oriented protocol
 DATAGRAM – uses UDP which is unreliable, message oriented protocol
 RAW – provides RAW data transfer directly over IP protocol (no transport
layer)
 Sockets can use
 “unicast” ( for a particular IP address destination)
 “multicast” ( a set of destinations – 224.x.x.x)
 “broadcast” (direct and limited)
 “Loopback” address i.e. 127.x.x.x
Socket programming
 Algorithm for TCP client
 Find the IP address and port number of server
 Create a TCP socket
 Connect the socket to server (Server must be up and listening for new
requests)
 Send/ receive data with server using the socket
 Close the connection
 Algorithm for TCP server
 Find the IP address and port number of server
 Create a TCP server socket
 Bind the server socket to server IP and Port number (this is the port to
which clients will connect)
 Accept a new connection from client
 returns a client socket that represents the client which is connected
 Send/ receive data with client using the client socket
 Close the connection with client
 Algorithm for UDP client
 Find the IP address and port number of server
 Create a UDP socket
 Send/ receive data with server using the socket
 Close the connection
 Algorithm for UDP server
 Find the IP address and port number of server
 Create a UDP server socket
 Bind the server socket to server IP and Port number (this is the port to
which clients will send)
 Send/ receive data with client using the client socket
 Close the connection with client
Socket programming
 Create the socket
 Identify the socket
 On the server, wait for an incoming connection
 On the client, connect to the server's socket
 Send and receive messages
 Close the socket
 Create a socket with the socket() system call
 Connect the socket to the address of the server using the connect() system
call
 Send and receive data. There are a number of ways to do this, but the simplest
is to use the send() and recv() system calls.
 Create a socket with the socket() system call
 Bind the socket to an address using the bind() system call. For a server socket
on the Internet, an address consists of a port number on the host machine.
 Listen for connections with the listen() system call
 Accept a connection with the accept() system call. This call typically blocks
until a client connects with the server.
 Send and receive data
Server Client
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
void error(char *msg){ perror(msg);exit(0);}
int main()
{
int sockfd;
int len;
struct sockaddr_in address;
int result;
char buffer[256};
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(socfd<0) { error(“Error opening Socket”);}
address.sin_family=AF_INET;
address.sin_addr.s_addr=inet_addr("192.168.70.202");
address.sin_port=htons(3333);
/* a structure to contain an internet address
defined in the include file <netinet/in.h> */
struct sockaddr_in {
short sin_family; /* should be AF_INET */
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /* not used, must be zero */
};
struct in_addr {
unsigned long s_addr;
};
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
void error(char *msg){ perror(msg);exit(0);}
int main()
{
int sockfd;
int len;
struct sockaddr_in address;
int result;
char buffer[256};
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(socfd<0) { error(“Error opening Socket”);}
address.sin_family=AF_INET;
address.sin_addr.s_addr=inet_addr("192.168.70.202");
address.sin_port=htons(3333);
Socket System Call – create an end point for
communication
#include <sys/types.h>
#include <sys/socket.h>
int socket(int domain, int type, int protocol);
Returns a descriptor
domain: selects protocol family
e.g. PF_IPX, PF_X25, PF_APPLETALK
type: specifies communication semantics
e.g. SOCK_DGRAM, SOCK_RAW
protocol: specifies a particular protocol to be used
e.g. IPPROTO_UDP, IPPROTO_ICMP
len=sizeof(address);
result=connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1)
{
error(“Error: Connecting");
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = recv(sockfd,buffer,255,0);
if (n < 0)
error("ERROR reading from socket");
printf("%sn",buffer);
close(sockfd);
exit(0);
}
Connect System Call – initiates a
connection on a socket
#include <sys/types.h>
#include <sys/socket.h>
int connect( int sockfd, const struct
sockaddr *serv_addr, socklen_t
addrlen);
Returns 0 on success
sockfd: descriptor that must refer to
a socket
serv_addr: address to which we
want to connect
addrlen: length of serv_addr
len=sizeof(address);
result=connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1)
{
error(“Error: Connecting");
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = recv(sockfd,buffer,255,0);
if (n < 0)
error("ERROR reading from socket");
printf("%sn",buffer);
close(sockfd);
exit(0);
}
Send System Call – send a
message to a socket
#include <sys/types.h>
#include <sys/socket.h>
int send( int s, const void *msg,
size_t len, int flags);
Returns number of characters sent
on success
s: descriptor that must refer to a
socket in connected state
msg: data that we want to send
len: length of data
flags: use default 0. MSG_OOB,
MSG_DONTWAIT
len=sizeof(address);
result=connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1)
{
error(“Error: Connecting");
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = recv(sockfd,buffer,255,0);
if (n < 0)
error("ERROR reading from socket");
printf("%sn",buffer);
close(sockfd);
exit(0);
}
Recv System Call – receive a
message from a socket
#include <sys/types.h>
#include <sys/socket.h>
int recv( int s, const void *buff,
size_t len, int flags);
Returns number of bytes received
on success
s: descriptor that must refer to a
socket in connected state
buff: data that we want to receive
len: length of data
flags: use default 0. MSG_OOB,
MSG_DONTWAIT
len=sizeof(address);
result=connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1)
{
error (“Error: Connecting ");
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = send(sockfd,buffer,strlen(buffer),0);
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = recv(sockfd,buffer,255,0);
if (n < 0)
error("ERROR reading from socket");
printf("%sn",buffer);
close(sockfd);
exit(0);
}
Close System Call – close a
socket descriptor
#include <unistd.h>
int close( int s);
Returns 0 on success
s: descriptor to be closed
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<sys/un.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
void error(char *msg){ perror(msg); exit(0);}
int main()
{
int server_sockfd,client_sockfd;
int server_len,client_len,n;
struct sockaddr_in server_address, client_address;
char buffer[256];
server_sockfd=socket(AF_INET,SOCK_STREAM,0);
if (sockfd < 0) error("ERROR opening socket");
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("192.168.70.1");
server_address.sin_port=htons(3333);
server_len=sizeof(server_address);
If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0)
error("ERROR on binding");
listen(server_sockfd,5);
client_len=sizeof(client_address);
client_sockfd=accept(server_sockfd,(struct sockaddr
*)&client_address,&client_len);
if(client_sockfd<0)
error("ERROR on Accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %sn",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket");
close(client_sockfd);
close(fd);
return 0;
}
Bind System Call – bind a name to
a socket
#include <sys/types.h>
#include <sys/socket.h>
int bind( int sockfd, const struct
sockaddr *serv_addr, socklen_t
addrlen);
Returns 0 on success
sockfd: descriptor that must refer
to a socket
serv_addr: address to which we
want to connect
addrlen: length of serv_addr
server_len=sizeof(server_address);
If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0)
error("ERROR on binding");
listen(server_sockfd,5);
client_len=sizeof(client_address);
client_sockfd=accept(server_sockfd,(struct sockaddr
*)&client_address,&client_len);
if(client_sockfd<0)
error("ERROR on Accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %sn",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket");
close(client_sockfd);
close(fd);
return 0;
}
Listen System Call – listen for
connections on a socket
#include <sys/types.h>
#include <sys/socket.h>
int listen( int s, int backlog);
Returns 0 on success
s: descriptor that must refer to a
socket
backlog: maximum length the
queue for completely established
sockets waiting to be accepted
addrlen: length of serv_addr
server_len=sizeof(server_address);
If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0)
error("ERROR on binding");
listen(server_sockfd,5);
client_len=sizeof(client_address);
client_sockfd=accept(server_sockfd,(struct sockaddr
*)&client_address,&client_len);
if(client_sockfd<0)
error("ERROR on Accept");
bzero(buffer,256);
n = recv(newsockfd,buffer,255,0);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %sn",buffer);
n = send(newsockfd,"I got your message",18,0);
if (n < 0) error("ERROR writing to socket");
close(client_sockfd);
close(fd);
return 0;
}
Accept System Call – accepts a
connection on a socket
#include <sys/types.h>
#include <sys/socket.h>
int accept( int sockfd, const struct
sockaddr *addr,
socklen_t addrlen);
Returns a non-negative descriptor
on success
sockfd: descriptor that must refer
to a socket
addr: filled with address of
connecting entity
addrlen: length of addr
 The client code for a datagram socket client is the same as that for a
stream socket with the following differences.
 the socket system call has SOCK_DGRAM instead of SOCK_STREAM as
its second argument & IPPROTO_UDP instead of IPPROTO_TCP as its
third argument.
 there is no connect() system call
 instead of send() and recv(), the client uses sendto() and recvfrom()
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
len = sizeof(struct sockaddr_in);
while (1) {
/* write */
n = sendto(sock,“Got your messagen",17, 0,(struct
sockaddr *) &server, len);
f (n < 0) error("sendto");
/* read */
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,
len);
if (n < 0) error("recvfrom");
}
 Server code with a datagram socket is similar to the stream socket code
with following differences.
 Servers using datagram sockets do not use the listen() or the accept()
system calls.
 After a socket has been bound to an address, the program calls
recvfrom() to read a message or sendto() to send a message.
sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
len = sizeof(struct sockaddr_in);
while (1) {
/* read */
n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from,
len);
if (n < 0) error("recvfrom");
/* write */
n = sendto(sock,"Got your messagen",17, 0,(struct
sockaddr *)&from, len);
f (n < 0) error("sendto");
}
 A socket, s, is created with the socket system call:
int s = socket(domain, type, protocol)
 Domain:-communication domain in which the socket should be created.
Some of address families are AF_INET (IP), AF_INET6 (IPv6), AF_UNIX
(local channel, similar to pipes), AF_ISO (ISO protocols), and AF_NS
(Xerox Network Systems protocols).
 Type:- type of service. This is selected according to the properties
required by the application: SOCK_STREAM (virtual circuit service),
SOCK_DGRAM (datagram service), SOCK_RAW (direct IP service).
Check with your address family to see whether a particular service is
available.
 Protocol:-indicate a specific protocol to use in supporting the sockets
operation. This is useful in cases where some families may have more than
one protocol to support a given type of service. The return value is a file
descriptor (a small integer). The analogy of creating a socket is that of
requesting a telephone line from the phone company.
For TCP/IP sockets, we want to specify the IP address family
(AF_INET) and virtual circuit service (SOCK_STREAM). Since there's
only one form of virtual circuit service, there are no variations of the
protocol, so the last argument, protocol, is zero. Our code for creating a
TCP socket looks like this:
fd = socket(AF_INET, SOCK_STREAM, 0)
 Stream Sockets: Delivery in a networked environment is guaranteed. If you
send through the stream socket three items "A,B,C", they will arrive in the
same order - "A,B,C". These sockets use TCP (Transmission Control Protocol)
for data transmission. If delivery is impossible, the sender receives an error
indicator. Data records do no have any boundaries.
 Datagram Sockets: Delivery in a networked environment is not guaranteed.
They're connectionless because you don't need to have an open connection as
in Stream Sockets - you build a packet with the destination information and
send it out. They use UDP (User Datagram Protocol).
 Raw Sockets: provides users access to the underlying communication
protocols which support socket abstractions. These sockets are normally
datagram oriented, though their exact characteristics are dependent on the
interface provided by the protocol. Raw sockets are not intended for the
general user; they have been provided mainly for those interested in
developing new communication protocols, or for gaining access to some of
the more esoteric facilities of an existing protocol.
 Sequenced Packet Sockets: Not used
 When we talk about naming a socket, we are talking about assigning a
transport address to the socket (a port number in IP networking). In sockets,
this operation is called binding an address and the bind system call is used for
this. The analogy is that of assigning a phone number to the line that you
requested from the phone company.
The transport address is defined in a socket address
structure. Because sockets were designed to work with various different types
of communication interfaces, the interface is very general. Instead of
accepting, say, a port number as a parameter, it takes a sockaddr structure
whose actual format is determined on the address family (type of network)
you're using. For example, if you're using UNIX domain sockets, bind actually
creates a file in the file system.
 htons :-host to network short : convert a number into a 16-bit network
representation. This is commonly used to store a port number into a sockaddr
structure.
 htonl :- host to network long : convert a number into a 32-bit network
representation. This is commonly used to store an IP address into a sockaddr
structure.
 ntohs :- network to host short : convert a 16-bit number from a network
representation into the local processor's format. This is commonly used to
read a port number from a sockaddr structure.
 ntohl :- network to host long : convert a 32-bit number from a network
representation into the local processor's format. This is commonly used to
read an IP address from a sockaddr structure.
 Before calling bind, we need to fill out this structure. The three key parts we
need to set are:
 sin_family :- The address family we used when we set up the socket. In
most of the Internet based applications we use AF_INET.
 sin_port :- The port number (the transport address). You can explicitly
assign a transport address (port) or allow the operating system to assign
one. If you're a client and won't be receiving incoming connections, you'll
usually just let the operating system pick any available port number by
specifying port 0. If you're a server, you'll generally pick a specific number
since clients will need to know a port number to connect to.
 sin_addr :-The address for this socket. This is just your machine's IP
address. With IP, your machine will have one IP address for each network
interface. For example, if your machine has both Wi-Fi and Ethernet
connections, that machine will have two addresses, one for each interface.
Most of the time, we don't care to specify a specific interface and can let
the operating system use whatever it wants. The special address for this is
0.0.0.0, defined by the symbolic constant INADDR_ANY.
Since the address structure may differ based on the
type of transport used, the third parameter specifies the length of that
structure. This is simply sizeof(struct sockaddr_in).
bind(int socket, const struct sockaddr *address,
socklen_t address_len);
 The first parameter, socket, is the socket that was created with the socket
system call.
 For the second parameter, the structure sockaddr is a generic container
that just allows the OS to be able to read the first couple of bytes that
identify the address family. The address family determines what variant of
the sockaddr struct to use that contains elements that make sense for that
specific communication type. For IP networking, we use struct
sockaddr_in, which is defined in the header netinet/in.h. This structure
defines:
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] };
 If we're a client process, we need to establish a connection to the server. Now
that we have a socket that knows where it's coming from, we need to tell it
where it's going to. The connect system call accomplishes this.
connect(int socket, const struct sockaddr *address, socklen_t
address_len);
The first parameter, socket, is the socket that was created with the socket
system call and named via bind. The second parameter identifies the remote
transport address using the same sockaddr_in structure that we used in bind
to identify our local address. As with bind, the third parameter is simply the
length of the structure in the second parameter: sizeof(struct sockaddr_in).
The server's address will contain the IP address of the server
machine as well as the port number that corresponds to a socket listening on
that port on that machine. The IP address is a four-byte (32 bit) value in
network byte order (see htonl above).
 Before a client can connect to a server, the server should have a socket that is
prepared to accept the connections. The listen system call tells a socket that it
should be capable of accepting incoming connections:
listen(int socket, int backlog);
The second parameter, backlog, defines the maximum number of pending
connections that can be queued up before connections are refused.
 The accept system call grabs the first connection request on the queue of
pending connections (set up in listen) and creates a new socket for that
connection. The original socket that was set up for listening is used only for
accepting connections, not for exchanging data. By default, socket operations
are synchronous, or blocking, and accept will block until a connection is
present on the queue. The syntax of accept is:
accept(int socket, struct sockaddr *restrict address,
socklen_t *restrict address_len);
The first parameter, socket, is the socket that was set for accepting
connections with listen.
The second parameter, address, is the address structure that gets filed in with
the address of the client that is doing the connect. This allows us to examine
the address and port number of the connecting socket if we want to.
The third parameter is filled in with the length of the address structure.
 We finally have connected sockets between a client and a server!
Communication is the easy part. The same read and write system calls that
work on files also work on sockets.
 We can send 20 bytes from the client to server with:
char buffer[MAXBUF];
nbytes = write(fd, buffer, 20); /* write 20 bytes in buffer */
 We can read a bunch of data from the client with:
char buffer[MAXBUF];
nbytes = read(fd, buffer, MAXBUF); /* read up to MAXBUF bytes */
• One important thing to keep in mind is that TCP/IP sockets give you a byte
stream, not a packet stream. If you write 20 bytes to a socket, the other side is
not guaranteed to read 20 bytes in a read operation. It may read 20. It may
read less if there was some packet fragmentation. In that case, you'll need to
loop back and keep reading. If you write 20 bytes to a socket and then write
another 20 bytes to a socket, the other side may read all 40 bytes at once ... or
not.
 When we're done communicating, the easiest thing to do is to close a socket
with the close system call — the same close that Is used for files.
Close();
Socket programming

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Socket programming
Socket programming Socket programming
Socket programming
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
UDP - User Datagram Protocol
UDP - User Datagram ProtocolUDP - User Datagram Protocol
UDP - User Datagram Protocol
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
 
Internet control message protocol
Internet control message protocolInternet control message protocol
Internet control message protocol
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
 
Static Routing
Static RoutingStatic Routing
Static Routing
 
ICMP
ICMPICMP
ICMP
 
Ch 19 Network-layer protocols Section 1
Ch 19  Network-layer protocols Section 1Ch 19  Network-layer protocols Section 1
Ch 19 Network-layer protocols Section 1
 
Socket programming or network programming
Socket programming or network programmingSocket programming or network programming
Socket programming or network programming
 
TCP Model
TCP ModelTCP Model
TCP Model
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP)
 
Address resolution protocol (ARP)
Address resolution protocol (ARP)Address resolution protocol (ARP)
Address resolution protocol (ARP)
 
Icmp
IcmpIcmp
Icmp
 

Ähnlich wie Socket programming

Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Socket Programming
Socket ProgrammingSocket Programming
Socket ProgrammingMostak Ahmed
 
Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8shanmuga priya
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure CallNadia Nahar
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in CDeepak Swain
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
Lan chat system
Lan chat systemLan chat system
Lan chat systemWipro
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.pptEloOgardo
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptsenthilnathans25
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 

Ähnlich wie Socket programming (20)

Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8Socket Programming Tutorial 1227317798640739 8
Socket Programming Tutorial 1227317798640739 8
 
Sockets
Sockets Sockets
Sockets
 
Os 2
Os 2Os 2
Os 2
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
 
Socket programming in C
Socket programming in CSocket programming in C
Socket programming in C
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
Lan chat system
Lan chat systemLan chat system
Lan chat system
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
Sockets
SocketsSockets
Sockets
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
 
A.java
A.javaA.java
A.java
 

Mehr von Anurag Tomar

Network interface card(nic)
Network interface card(nic)Network interface card(nic)
Network interface card(nic)Anurag Tomar
 
Serial Peripheral Interface
Serial Peripheral InterfaceSerial Peripheral Interface
Serial Peripheral InterfaceAnurag Tomar
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger TutorialAnurag Tomar
 
Software development process basic
Software development process basicSoftware development process basic
Software development process basicAnurag Tomar
 

Mehr von Anurag Tomar (6)

Network interface card(nic)
Network interface card(nic)Network interface card(nic)
Network interface card(nic)
 
I2C Protocol
I2C ProtocolI2C Protocol
I2C Protocol
 
Serial Peripheral Interface
Serial Peripheral InterfaceSerial Peripheral Interface
Serial Peripheral Interface
 
Valgrind debugger Tutorial
Valgrind debugger TutorialValgrind debugger Tutorial
Valgrind debugger Tutorial
 
Software development process basic
Software development process basicSoftware development process basic
Software development process basic
 
SPI Protocol
SPI ProtocolSPI Protocol
SPI Protocol
 

Kürzlich hochgeladen

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 

Kürzlich hochgeladen (20)

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 

Socket programming

  • 2.  Introduction to Sockets  A generic Client-Server application  Programming Client-Server in C  References
  • 4.  Why Sockets?  Used for Interprocess Communication.  The Client-Server model  Most Interprocess Communication uses client-server model  Client & Server are two processes that wants to communicate with each other  The Client process connects to the Server process, to make a request for information/services own by the Server.  Once the connection is established between Client process and Server process, they can start sending / receiving information.  What are Sockets?  End-point of Interprocess Communication.  allows communication between two different processes on the same or different machines  An interface through which processes can send / receive information. Socket
  • 5.  What exactly creates a Socket?  <IP address, Port #> tuple  What makes a connection?  {Source<IP address, Port #> , Destination <IP address, Port #>} i.e. source socket – destination socket pair uniquely identifies a connection.  Example Server 192.168.0.1 Client Client Client 192.168.0.2 192.168.0.2 192.168.0.3 80 1343 1343 5488
  • 6.  Socket Types  STREAM – uses TCP which is reliable, stream oriented protocol  DATAGRAM – uses UDP which is unreliable, message oriented protocol  RAW – provides RAW data transfer directly over IP protocol (no transport layer)  Sockets can use  “unicast” ( for a particular IP address destination)  “multicast” ( a set of destinations – 224.x.x.x)  “broadcast” (direct and limited)  “Loopback” address i.e. 127.x.x.x
  • 8.  Algorithm for TCP client  Find the IP address and port number of server  Create a TCP socket  Connect the socket to server (Server must be up and listening for new requests)  Send/ receive data with server using the socket  Close the connection  Algorithm for TCP server  Find the IP address and port number of server  Create a TCP server socket  Bind the server socket to server IP and Port number (this is the port to which clients will connect)  Accept a new connection from client  returns a client socket that represents the client which is connected  Send/ receive data with client using the client socket  Close the connection with client
  • 9.  Algorithm for UDP client  Find the IP address and port number of server  Create a UDP socket  Send/ receive data with server using the socket  Close the connection  Algorithm for UDP server  Find the IP address and port number of server  Create a UDP server socket  Bind the server socket to server IP and Port number (this is the port to which clients will send)  Send/ receive data with client using the client socket  Close the connection with client
  • 11.  Create the socket  Identify the socket  On the server, wait for an incoming connection  On the client, connect to the server's socket  Send and receive messages  Close the socket
  • 12.  Create a socket with the socket() system call  Connect the socket to the address of the server using the connect() system call  Send and receive data. There are a number of ways to do this, but the simplest is to use the send() and recv() system calls.
  • 13.  Create a socket with the socket() system call  Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.  Listen for connections with the listen() system call  Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.  Send and receive data
  • 15. #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<sys/un.h> #include<netinet/in.h> #include<arpa/inet.h> #include<fcntl.h> void error(char *msg){ perror(msg);exit(0);} int main() { int sockfd; int len; struct sockaddr_in address; int result; char buffer[256}; sockfd=socket(AF_INET,SOCK_STREAM,0); if(socfd<0) { error(“Error opening Socket”);} address.sin_family=AF_INET; address.sin_addr.s_addr=inet_addr("192.168.70.202"); address.sin_port=htons(3333); /* a structure to contain an internet address defined in the include file <netinet/in.h> */ struct sockaddr_in { short sin_family; /* should be AF_INET */ u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; /* not used, must be zero */ }; struct in_addr { unsigned long s_addr; };
  • 16. #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<sys/un.h> #include<netinet/in.h> #include<arpa/inet.h> #include<fcntl.h> void error(char *msg){ perror(msg);exit(0);} int main() { int sockfd; int len; struct sockaddr_in address; int result; char buffer[256}; sockfd=socket(AF_INET,SOCK_STREAM,0); if(socfd<0) { error(“Error opening Socket”);} address.sin_family=AF_INET; address.sin_addr.s_addr=inet_addr("192.168.70.202"); address.sin_port=htons(3333); Socket System Call – create an end point for communication #include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); Returns a descriptor domain: selects protocol family e.g. PF_IPX, PF_X25, PF_APPLETALK type: specifies communication semantics e.g. SOCK_DGRAM, SOCK_RAW protocol: specifies a particular protocol to be used e.g. IPPROTO_UDP, IPPROTO_ICMP
  • 17. len=sizeof(address); result=connect(sockfd,(struct sockaddr *)&address,len); if(result == -1) { error(“Error: Connecting"); } printf("Please enter the message: "); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("%sn",buffer); close(sockfd); exit(0); } Connect System Call – initiates a connection on a socket #include <sys/types.h> #include <sys/socket.h> int connect( int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); Returns 0 on success sockfd: descriptor that must refer to a socket serv_addr: address to which we want to connect addrlen: length of serv_addr
  • 18. len=sizeof(address); result=connect(sockfd,(struct sockaddr *)&address,len); if(result == -1) { error(“Error: Connecting"); } printf("Please enter the message: "); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("%sn",buffer); close(sockfd); exit(0); } Send System Call – send a message to a socket #include <sys/types.h> #include <sys/socket.h> int send( int s, const void *msg, size_t len, int flags); Returns number of characters sent on success s: descriptor that must refer to a socket in connected state msg: data that we want to send len: length of data flags: use default 0. MSG_OOB, MSG_DONTWAIT
  • 19. len=sizeof(address); result=connect(sockfd,(struct sockaddr *)&address,len); if(result == -1) { error(“Error: Connecting"); } printf("Please enter the message: "); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("%sn",buffer); close(sockfd); exit(0); } Recv System Call – receive a message from a socket #include <sys/types.h> #include <sys/socket.h> int recv( int s, const void *buff, size_t len, int flags); Returns number of bytes received on success s: descriptor that must refer to a socket in connected state buff: data that we want to receive len: length of data flags: use default 0. MSG_OOB, MSG_DONTWAIT
  • 20. len=sizeof(address); result=connect(sockfd,(struct sockaddr *)&address,len); if(result == -1) { error (“Error: Connecting "); } printf("Please enter the message: "); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("%sn",buffer); close(sockfd); exit(0); } Close System Call – close a socket descriptor #include <unistd.h> int close( int s); Returns 0 on success s: descriptor to be closed
  • 21. #include<sys/types.h> #include<sys/socket.h> #include<stdio.h> #include<sys/un.h> #include<netinet/in.h> #include<arpa/inet.h> #include<fcntl.h> void error(char *msg){ perror(msg); exit(0);} int main() { int server_sockfd,client_sockfd; int server_len,client_len,n; struct sockaddr_in server_address, client_address; char buffer[256]; server_sockfd=socket(AF_INET,SOCK_STREAM,0); if (sockfd < 0) error("ERROR opening socket"); server_address.sin_family=AF_INET; server_address.sin_addr.s_addr=inet_addr("192.168.70.1"); server_address.sin_port=htons(3333);
  • 22. server_len=sizeof(server_address); If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0) error("ERROR on binding"); listen(server_sockfd,5); client_len=sizeof(client_address); client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address,&client_len); if(client_sockfd<0) error("ERROR on Accept"); bzero(buffer,256); n = recv(newsockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %sn",buffer); n = send(newsockfd,"I got your message",18,0); if (n < 0) error("ERROR writing to socket"); close(client_sockfd); close(fd); return 0; } Bind System Call – bind a name to a socket #include <sys/types.h> #include <sys/socket.h> int bind( int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); Returns 0 on success sockfd: descriptor that must refer to a socket serv_addr: address to which we want to connect addrlen: length of serv_addr
  • 23. server_len=sizeof(server_address); If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0) error("ERROR on binding"); listen(server_sockfd,5); client_len=sizeof(client_address); client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address,&client_len); if(client_sockfd<0) error("ERROR on Accept"); bzero(buffer,256); n = recv(newsockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %sn",buffer); n = send(newsockfd,"I got your message",18,0); if (n < 0) error("ERROR writing to socket"); close(client_sockfd); close(fd); return 0; } Listen System Call – listen for connections on a socket #include <sys/types.h> #include <sys/socket.h> int listen( int s, int backlog); Returns 0 on success s: descriptor that must refer to a socket backlog: maximum length the queue for completely established sockets waiting to be accepted addrlen: length of serv_addr
  • 24. server_len=sizeof(server_address); If(bind(server_sockfd,(struct sockaddr*)&server_address,server_len)<0) error("ERROR on binding"); listen(server_sockfd,5); client_len=sizeof(client_address); client_sockfd=accept(server_sockfd,(struct sockaddr *)&client_address,&client_len); if(client_sockfd<0) error("ERROR on Accept"); bzero(buffer,256); n = recv(newsockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %sn",buffer); n = send(newsockfd,"I got your message",18,0); if (n < 0) error("ERROR writing to socket"); close(client_sockfd); close(fd); return 0; } Accept System Call – accepts a connection on a socket #include <sys/types.h> #include <sys/socket.h> int accept( int sockfd, const struct sockaddr *addr, socklen_t addrlen); Returns a non-negative descriptor on success sockfd: descriptor that must refer to a socket addr: filled with address of connecting entity addrlen: length of addr
  • 25.  The client code for a datagram socket client is the same as that for a stream socket with the following differences.  the socket system call has SOCK_DGRAM instead of SOCK_STREAM as its second argument & IPPROTO_UDP instead of IPPROTO_TCP as its third argument.  there is no connect() system call  instead of send() and recv(), the client uses sendto() and recvfrom() sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); len = sizeof(struct sockaddr_in); while (1) { /* write */ n = sendto(sock,“Got your messagen",17, 0,(struct sockaddr *) &server, len); f (n < 0) error("sendto"); /* read */ n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len); if (n < 0) error("recvfrom"); }
  • 26.  Server code with a datagram socket is similar to the stream socket code with following differences.  Servers using datagram sockets do not use the listen() or the accept() system calls.  After a socket has been bound to an address, the program calls recvfrom() to read a message or sendto() to send a message. sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); len = sizeof(struct sockaddr_in); while (1) { /* read */ n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len); if (n < 0) error("recvfrom"); /* write */ n = sendto(sock,"Got your messagen",17, 0,(struct sockaddr *)&from, len); f (n < 0) error("sendto"); }
  • 27.  A socket, s, is created with the socket system call: int s = socket(domain, type, protocol)  Domain:-communication domain in which the socket should be created. Some of address families are AF_INET (IP), AF_INET6 (IPv6), AF_UNIX (local channel, similar to pipes), AF_ISO (ISO protocols), and AF_NS (Xerox Network Systems protocols).  Type:- type of service. This is selected according to the properties required by the application: SOCK_STREAM (virtual circuit service), SOCK_DGRAM (datagram service), SOCK_RAW (direct IP service). Check with your address family to see whether a particular service is available.
  • 28.  Protocol:-indicate a specific protocol to use in supporting the sockets operation. This is useful in cases where some families may have more than one protocol to support a given type of service. The return value is a file descriptor (a small integer). The analogy of creating a socket is that of requesting a telephone line from the phone company. For TCP/IP sockets, we want to specify the IP address family (AF_INET) and virtual circuit service (SOCK_STREAM). Since there's only one form of virtual circuit service, there are no variations of the protocol, so the last argument, protocol, is zero. Our code for creating a TCP socket looks like this: fd = socket(AF_INET, SOCK_STREAM, 0)
  • 29.  Stream Sockets: Delivery in a networked environment is guaranteed. If you send through the stream socket three items "A,B,C", they will arrive in the same order - "A,B,C". These sockets use TCP (Transmission Control Protocol) for data transmission. If delivery is impossible, the sender receives an error indicator. Data records do no have any boundaries.  Datagram Sockets: Delivery in a networked environment is not guaranteed. They're connectionless because you don't need to have an open connection as in Stream Sockets - you build a packet with the destination information and send it out. They use UDP (User Datagram Protocol).  Raw Sockets: provides users access to the underlying communication protocols which support socket abstractions. These sockets are normally datagram oriented, though their exact characteristics are dependent on the interface provided by the protocol. Raw sockets are not intended for the general user; they have been provided mainly for those interested in developing new communication protocols, or for gaining access to some of the more esoteric facilities of an existing protocol.  Sequenced Packet Sockets: Not used
  • 30.  When we talk about naming a socket, we are talking about assigning a transport address to the socket (a port number in IP networking). In sockets, this operation is called binding an address and the bind system call is used for this. The analogy is that of assigning a phone number to the line that you requested from the phone company. The transport address is defined in a socket address structure. Because sockets were designed to work with various different types of communication interfaces, the interface is very general. Instead of accepting, say, a port number as a parameter, it takes a sockaddr structure whose actual format is determined on the address family (type of network) you're using. For example, if you're using UNIX domain sockets, bind actually creates a file in the file system.
  • 31.  htons :-host to network short : convert a number into a 16-bit network representation. This is commonly used to store a port number into a sockaddr structure.  htonl :- host to network long : convert a number into a 32-bit network representation. This is commonly used to store an IP address into a sockaddr structure.  ntohs :- network to host short : convert a 16-bit number from a network representation into the local processor's format. This is commonly used to read a port number from a sockaddr structure.  ntohl :- network to host long : convert a 32-bit number from a network representation into the local processor's format. This is commonly used to read an IP address from a sockaddr structure.
  • 32.  Before calling bind, we need to fill out this structure. The three key parts we need to set are:  sin_family :- The address family we used when we set up the socket. In most of the Internet based applications we use AF_INET.  sin_port :- The port number (the transport address). You can explicitly assign a transport address (port) or allow the operating system to assign one. If you're a client and won't be receiving incoming connections, you'll usually just let the operating system pick any available port number by specifying port 0. If you're a server, you'll generally pick a specific number since clients will need to know a port number to connect to.  sin_addr :-The address for this socket. This is just your machine's IP address. With IP, your machine will have one IP address for each network interface. For example, if your machine has both Wi-Fi and Ethernet connections, that machine will have two addresses, one for each interface. Most of the time, we don't care to specify a specific interface and can let the operating system use whatever it wants. The special address for this is 0.0.0.0, defined by the symbolic constant INADDR_ANY. Since the address structure may differ based on the type of transport used, the third parameter specifies the length of that structure. This is simply sizeof(struct sockaddr_in).
  • 33. bind(int socket, const struct sockaddr *address, socklen_t address_len);  The first parameter, socket, is the socket that was created with the socket system call.  For the second parameter, the structure sockaddr is a generic container that just allows the OS to be able to read the first couple of bytes that identify the address family. The address family determines what variant of the sockaddr struct to use that contains elements that make sense for that specific communication type. For IP networking, we use struct sockaddr_in, which is defined in the header netinet/in.h. This structure defines: 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] };
  • 34.  If we're a client process, we need to establish a connection to the server. Now that we have a socket that knows where it's coming from, we need to tell it where it's going to. The connect system call accomplishes this. connect(int socket, const struct sockaddr *address, socklen_t address_len); The first parameter, socket, is the socket that was created with the socket system call and named via bind. The second parameter identifies the remote transport address using the same sockaddr_in structure that we used in bind to identify our local address. As with bind, the third parameter is simply the length of the structure in the second parameter: sizeof(struct sockaddr_in). The server's address will contain the IP address of the server machine as well as the port number that corresponds to a socket listening on that port on that machine. The IP address is a four-byte (32 bit) value in network byte order (see htonl above).
  • 35.  Before a client can connect to a server, the server should have a socket that is prepared to accept the connections. The listen system call tells a socket that it should be capable of accepting incoming connections: listen(int socket, int backlog); The second parameter, backlog, defines the maximum number of pending connections that can be queued up before connections are refused.
  • 36.  The accept system call grabs the first connection request on the queue of pending connections (set up in listen) and creates a new socket for that connection. The original socket that was set up for listening is used only for accepting connections, not for exchanging data. By default, socket operations are synchronous, or blocking, and accept will block until a connection is present on the queue. The syntax of accept is: accept(int socket, struct sockaddr *restrict address, socklen_t *restrict address_len); The first parameter, socket, is the socket that was set for accepting connections with listen. The second parameter, address, is the address structure that gets filed in with the address of the client that is doing the connect. This allows us to examine the address and port number of the connecting socket if we want to. The third parameter is filled in with the length of the address structure.
  • 37.  We finally have connected sockets between a client and a server! Communication is the easy part. The same read and write system calls that work on files also work on sockets.  We can send 20 bytes from the client to server with: char buffer[MAXBUF]; nbytes = write(fd, buffer, 20); /* write 20 bytes in buffer */  We can read a bunch of data from the client with: char buffer[MAXBUF]; nbytes = read(fd, buffer, MAXBUF); /* read up to MAXBUF bytes */ • One important thing to keep in mind is that TCP/IP sockets give you a byte stream, not a packet stream. If you write 20 bytes to a socket, the other side is not guaranteed to read 20 bytes in a read operation. It may read 20. It may read less if there was some packet fragmentation. In that case, you'll need to loop back and keep reading. If you write 20 bytes to a socket and then write another 20 bytes to a socket, the other side may read all 40 bytes at once ... or not.
  • 38.  When we're done communicating, the easiest thing to do is to close a socket with the close system call — the same close that Is used for files. Close();

Hinweis der Redaktion

  1. For processors that use the big endian format, these macros do absolutely nothing. For those that use the little endian format (most processors, these days), the macros flip the sequence of either four or two bytes. In the above code, writing htonl(INADDR_ANY) and htons(0) is somewhat pointless since all the bytes are zero anyway but it's good practice to remember to do this at all times when reading or writing network data.