0% found this document useful (0 votes)
2 views

Unit 1_Network

This document provides an overview of network programming concepts, including the OSI model, TCP/IP protocols, and socket programming in Java. It explains the roles of clients and servers, the differences between TCP and UDP, and includes code examples for creating client-server applications. Additionally, it covers the use of port numbers, URL handling, and basic socket operations in Java.

Uploaded by

meghpatel2022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Unit 1_Network

This document provides an overview of network programming concepts, including the OSI model, TCP/IP protocols, and socket programming in Java. It explains the roles of clients and servers, the differences between TCP and UDP, and includes code examples for creating client-server applications. Additionally, it covers the use of port numbers, URL handling, and basic socket operations in Java.

Uploaded by

meghpatel2022
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Network programming

Chapter 1
By: Prof. Bijal Gadhia(GECG)
What is network??
•Interconnection of computers and devices
either by using a cable or satellite link where no
cable is needed.
–Client: Receives service
–Server: Provides service.
The OSI Model
TCP/IP and OSI model
Addresses in the TCP/IP protocol suite
TCP and UDP are end-to-end protocols:
Which means they are executed on the end points
(hosts).
The Internet supports 2 transport protocols.

UDP - User Datagram Protocol TCP - Transmission Control Protocol


•datagram oriented •stream oriented
•unreliable, connectionless •reliable, connection-oriented
•simple •complex
•unicast and multicast •only unicast
•useful for multimedia applications •used for data applications:
•used for control protocols –web (http), email (smtp), file
–Network Management (SNMP), transfer (ftp), SecureCRT, etc.
routing (RIP), naming (DNS), etc.
Port Number:
A port number identifies the endpoint of a connection/Process on a machine.

A pair <IP address, port number> identifies one endpoint of a connection.


Two pairs <client IP address, client port number> and <server IP
address, server port number> identify a TCP connection.
Port no. and Protocols:
20 & 21: File Transfer Protocol (FTP)
22: Secure Shell (SSH)
23: Telnet remote login service
25: Simple Mail Transfer Protocol (SMTP)
53: Domain Name System (DNS) service
80: Hypertext Transfer Protocol (HTTP)
110: Post Office Protocol (POP3)
119: Network News Transfer Protocol (NNTP)
143: Internet Message Access Protocol (IMAP)
161: Simple Network Management Protocol (SNMP)
443: HTTP Secure (HTTPS)
URL (Uniform Resource Locator)

Port numbers can occasionally be seen in a web or


other service.
Ex. Like
uniform resource locator (URL).
By default, HTTP uses port 80 and HTTPS uses port
443, but a URL like
http://www.example.com:80/path/
be served by the HTTP server on port 8080.
Network Programming with JAVA using java.net
package

Knowing IP Address:
import java.net.*;
import java.io.*;

public class GetIPAddress {


public static void main(String [] args) {
try {
InetAddress thisIp =InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
import java.io.*;
import java.net.*;
public class GetIPAddress
{
public static void main(String[] args){
try
{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{System.out.println(e);}
}
}
OUTPUT:
import java.net.*;
import java.io.*;
public class MyUrl {
public static void main(String a[])throws IOException
{

URL obj= new URL("http://www.tutorialspoint.com/java/java_sending_email.htm");

System.out.println("Protocol:"+obj.getProtocol());
System.out.println("Host:"+obj.getHost());
System.out.println("File:"+obj.getFile());
System.out.println("Port:"+obj.getPort());
System.out.println("ExternalForm:"+obj.toExternalForm());
}
}
OUTPUT:
Program to Demonstrate URLConnection class.

import java.io.*;
import java.net.*;
import java.util.*;

public class URLDETAILS {

public static void main(String a[]) throws IOException


{

URL obj=new URL("http://www.tutorialspoint.com/java/java_sending_email.htm");


URLConnection conn=obj.openConnection();
System.out.println("Date:"+ new Date(conn.getDate()));
System.out.println("Content-type:"+ conn.getContentType());
System.out.println("Expiry:"+ (conn.getExpiration()));
System.out.println("Last Modified"+ conn.getLastModified());
int l=conn.getContentLength();
System.out.print("Length of Content:"+l);
if(l==0)
{
System.out.println("Content Not Available");
}
else{

int ch;
InputStream in= conn.getInputStream();
while((ch=in.read())!=-1)
{
System.out.print((char)ch);
}
}
}

}
OUTPUT:
import java.io.*;
import java.net.*;
public class GetIPAddress
{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e){
System.out.println(e);
}
}
}
What is a socket?
•Socket
–The combination of an IP address and a port number.
–Two types
•Stream socket : reliable two-way connected communication streams
•Datagram socket

•Socket pair
–Specified the two end points that uniquely identifies each TCP connection
in an internet.
–4-tuple: (client IP address, client port number, server IP address, server
port number)
Client-server applications
•Implementation of a protocol standard defined . (FTP, HTTP, SMTP…)
–Should use the port number associated with the protocol.

•Proprietary client-server application.


–A single developer( or team) creates both client and server program.
–The developer has complete control.
–Must be careful not to use one of the well-known port number defined

Socket Programming with TCP

Figure 2.6-1: Processes communicating through TCP sockets

The application developer has the ability to fix a few TCP


parameters, such as maximum buffer and maximum segment sizes.
Sockets for server and client
•Server
–Welcoming socket
•Welcomes some initial contact from a client.
–Connection socket
•Is created at initial contact of client.
•New socket that is dedicated to the particular client.

•Client
–Client socket
•Initiate a TCP connection to the server by creating a socket object.
(Three-way handshake)
•Specify the address of the server process, namely, the IP address of
the server and the port number of the process.
Socket functional calls
•socket (): Create a socket
•bind(): bind a socket to a local IP address and port #
•listen(): passively waiting for connections
•connect(): initiating connection to another socket
•accept(): accept a new connection
•Write(): write data to a socket
•Read(): read data from a socket
•sendto(): send a datagram to another UDP socket
•recvfrom(): read a datagram from a UDP socket
•close(): close a socket (tear down the connection)
Sockets

Figure 2.6-2: Client socket, welcoming socket and connection socket


Socket-programming using TCP
TCP service: reliable byte stream transfer
socket( )
server
socket( )
client
TCP conn. request
accept( )
send( ) TCP ACK
recv( )

recv( )
send( )
close( ) close( )

controlled by
application process
process
developer socket
socket
controlled by TCP with
TCP with
operating buffers, internet
system buffers,
variables
variables
Socket programming with TCP

Example client-server app:


•client reads line from standard
input (inFromUser stream) ,
sends to server via socket Client
Input stream:
(outToServer stream) process sequence of bytes
•server reads line from socket into process
output stream:
•Server sends some string to sequence of bytes
client. out of process
•client reads, prints modified line
from socket (inFromServer
stream)
client TCP
socket
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
JAVA TCP Sockets
•In Package java.net
–java.net.Socket
•Implements client sockets (also called just “sockets”).
•An endpoint for communication between two machines.
•Constructor and Methods

–Socket(String host, int port): Creates a stream socket and connects


it to the specified port number on the named host.
–InputStream getInputStream()
–OutputStream getOutputStream()
–close()

–java.net.ServerSocket
•Implements server sockets.
•Waits for requests to come in over the network.
•Performs some operation based on the request.
•Constructor and Methods

–ServerSocket(int port)
–Socket Accept(): Listens for a connection to be made to this socket
and accepts it. This method blocks until a connection is made.
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket(“localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
TCPClient.java
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new
ServerSocket(6789);
while(true) {
Socket connectionSocket =
welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
TCPServer.java

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
Run Server

Run Client
Write some string

On client Side get


some answer by server
A
Chat Application
of
Client and Server
Client Server
ChatClient.java
import java.net.*;
import java.io.*;
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("localhost",2000);

BufferedReader sin=new BufferedReader(new


InputStreamReader(sk.getInputStream()));
PrintStream sout=new PrintStream(sk.getOutputStream());

BufferedReader stdin=new BufferedReader(new


InputStreamReader(System.in));
String s;
while ( true )
{
System.out.print("Client : ");
s=stdin.readLine();
sout.println(s);
s=sin.readLine();
System.out.print("Server : "+s+"\n");
if ( s.equalsIgnoreCase("BYE") )
break;
}
sk.close();
sin.close();
sout.close();
stdin.close();
}
}
ChatServer.java
import java.net.*;
import java.io.*;
public class chatserver {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=ss.accept();

BufferedReader cin=new BufferedReader(new


InputStreamReader(sk.getInputStream()));
PrintStream cout=new PrintStream(sk.getOutputStream());
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String s;
while ( true )
{ s=cin.readLine();
if (s.equalsIgnoreCase(“BYE"))
{
cout.println("BYE"); break; }
System. out.print("Client : "+s+"\n");
System.out.print("Server : ");
s=stdin.readLine();
cout.println(s);
}
ss.close();
sk.close();
cin.close();
cout.close();
stdin.close(); } }
UDPServer.java
import java.io.*;
import java.net.*;
public class UDPClient
{
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 7777;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
try
{
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
while(true)
{
//take input and send the packet
echo("Enter message to send : ");
s = (String)cin.readLine();
byte[] b = s.getBytes();
DatagramPacket dp = new DatagramPacket(b , b.length , host , port);
sock.send(dp);
UDPServer.java
//now receive reply
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);

byte[] data = reply.getData();


s = new String(data, 0, reply.getLength());

//echo the details of incoming data - client ip : client port - client message

echo(reply.getAddress().getHostAddress() + " : " + reply.getPort() + " - " + s);

}
}

catch(IOException e)
{
System.err.println("IOException " + e);
}
}

//simple function to echo data to terminal


public static void echo(String msg)
{
System.out.println(msg);
}
}
UDPClient.java
import java.io.*;
import java.net.*;

public class UDPClient


{
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 7777;
String s;

BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));

try
{
sock = new DatagramSocket();

InetAddress host = InetAddress.getByName("localhost");

while(true)
{
//take input and send the packet
echo("Enter message to send : ");
s = (String)cin.readLine();
byte[] b = s.getBytes();
UDPClient.java
DatagramPacket dp = new DatagramPacket(b , b.length , host , port);
sock.send(dp);
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
s = new String(data, 0, reply.getLength());

//echo the details of incoming data - client ip : client port - client message
echo(reply.getAddress().getHostAddress() + " : " + reply.getPort() + " - " + s);
}
}
catch(IOException e)
{
System.err.println("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
System.out.println(msg);
}
}
public class udpBaseServer_2
{
public static void main(String[] args) throws IOException

DatagramSocket ds = new DatagramSocket(5551);


byte[] receive = new byte[65535];
DatagramPacket DpReceive = null;
while (true)
{

DpReceive = new DatagramPacket(receive, receive.length);

ds.receive(DpReceive);

System.out.println("Client:-" + data(receive));

if (data(receive).toString().equals("bye"))
{
System.out.println("Client sent bye.....EXITING");
break;
}

receive = new byte[65535];


}
}

public static StringBuilder data(byte[] a)


{
if (a == null)
return null;
StringBuilder ret = new StringBuilder();
int i = 0;
while (a[i] != 0)
{
ret.append((char) a[i]);
i++;
}
return ret;
}
}
public class udpBaseClient_2
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);

DatagramSocket ds = new DatagramSocket();

InetAddress ip = InetAddress.getLocalHost();
byte buf[] = null;

while (true)
{
String inp = sc.nextLine();

buf = inp.getBytes();

DatagramPacket DpSend =new DatagramPacket(buf, buf.length, ip, 5551);


ds.send(DpSend);

if (inp.equals("bye"))

break;
}
}
}

You might also like