1. Assignment No # 2
Group members:
Syed Hamid Raza-016
Muhammad Feezan-021
Zia Ul Hassan-027
Subject:
Operatingsystem
Submitted to:
Sir Hafiz Usman Zia
2. Topic: Sockets
The network concept of a socket refers to the connection of one host to another
through the combination of compatible IP Addresses and ports.
Sockets are the receiving endpoints of a connection and the attached connections
between the sockets linking two separate hosts called Threads.
Used for communication in client server system.
It is an interface of client server architecture.
Sockets are the low level endpoint used for processing information across a
network.
Defined as end point for communication.
A socket is identified by IP address concatenated with port numbers.
Client: Ask for information from server.
Server: Response of client request.
Used for establishing both server client connection.
Specific services of server that implemented (ftp, http).
(Above services listen specific ports numbers that are reserved for these specific
services).
3. Socket Types
o Internet socket
o Unix socket
o X.25 Socket etc…..
Internet Socket
Internet Sockets characterized by IP address (4 bytes) and port number (2
bytes).
It’s Transport Layer Protocol.
Typesof internetsocket
1) Stream Socket
a) Connection oriented
b) Rely on TCP to provide two-way communication.
2) Datagram Socket
a) Connection is unreliable.
b) Rely on UDP.
User Datagram Protocol
1) Message oriented.
2) No connection is established.
3) Light weight.
4) Small packet size UDP header- 8 bytes.
5) No error detection.
6) Data can’t have retrieved.
7) Corrupted data may be discarded or lead to out of order.
4. Types:
Connection oriented(TCP):
Known as reliable network services because data arrive in proper
sequence. For connection-oriented communications, each end point must
be able to transmit so that it can communicate.
Connection less (UDP):
Connectionless sockets do not establish a connection over which
data is transferred. Instead, the server application specifies its name
where a client can send requests.
Multicastsocket:
Data can be sent to multiple recipients.
Telephone Analogy
A telephone call over a telephony network works as follows:
Both parties should have telephone.
Both are assigned their specific numbers.
Turn on a ringer to listen for a caller.
Caller lifts telephone and dials a number.
Telephone rings and the receiver of the call picks it.
Both parties talk and exchange data.
After conversation is done they hang up the phone.
Dissecting the Analogy
An endpoint (telephone) for communication is created on both sides.
An address is assigned to both networks.
One of them initiate the connection.
Other will wait for establishment of connection.
Once connection is established, data is exchanged.
After data is exchanged, endpoints are closed.
5. Real life Examples
Common networking protocol’s like HTTP, FTP rely on sockets
underneath to make connections.
WWW (web pages) and all the browsers like google chrome,
Mozilla Firefox, Internet explorer etc…
P2P network (LimeWire, BitComet)
Telephone call is just work on the principle of sockets.
Socket programming/process
Socket programming is a way of connecting two nodes on a network to
communicate with each other. One socket (node) listens on a particular port at
an IP, while other socket reaches out to the other to form a connection. Server
forms the listener socket while client reaches out to the server.
IN C++
Server Side
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
6. int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%sn",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sentn");
return 0;
}
7. Client Side
// Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("n Socket creation error n");
return -1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("nInvalid address/ Address not supported n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr,
sizeof(serv_addr)) < 0)
{
printf("nConnection Failed n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
printf("Hello message sentn");
valread = read( sock , buffer, 1024);
printf("%sn",buffer );
8. return 0;
}
In JAVA From Book
import java.net.*;
import java.io.*;
public class DateServer
{
public static void main(String[] args) {
try {
ServerSocket sock = new ServerSocket(6013);
/* now listen for connections */
while (true) {
Socket client = sock.accept();
PrintWriter pout = new
PrintWriter(client.getOutputStream(), true);
/* write the Date to the socket */
pout.println(new java.util.Date().toString());
/* close the socket and resume */
/* listening for connections */
client.close();
}
}
catch (IOException ioe) {
System.err.println(ioe);
}
From Google
Client Side
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
9. public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over"))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
10. }
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
Server Side
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{