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
[Link]
be served by the HTTP server on port 8080.
Network Programming with JAVA using [Link]
package
Knowing IP Address:
import [Link].*;
import [Link].*;
public class GetIPAddress {
public static void main(String [] args) {
try {
InetAddress thisIp =[Link]();
[Link]("IP:"+[Link]());
}
catch(Exception e) {
[Link]();
}
}
}
OUTPUT:
import [Link].*;
import [Link].*;
public class GetIPAddress
{
public static void main(String[] args){
try
{
InetAddress ip=[Link]("[Link]");
[Link]("Host Name: "+[Link]());
[Link]("IP Address: "+[Link]());
}
catch(Exception e)
{[Link](e);}
}
}
OUTPUT:
import [Link].*;
import [Link].*;
public class MyUrl {
public static void main(String a[])throws IOException
{
URL obj= new URL("[Link]
[Link]("Protocol:"+[Link]());
[Link]("Host:"+[Link]());
[Link]("File:"+[Link]());
[Link]("Port:"+[Link]());
[Link]("ExternalForm:"+[Link]());
}
}
OUTPUT:
Program to Demonstrate URLConnection class.
import [Link].*;
import [Link].*;
import [Link].*;
public class URLDETAILS {
public static void main(String a[]) throws IOException
{
URL obj=new URL("[Link]
URLConnection conn=[Link]();
[Link]("Date:"+ new Date([Link]()));
[Link]("Content-type:"+ [Link]());
[Link]("Expiry:"+ ([Link]()));
[Link]("Last Modified"+ [Link]());
int l=[Link]();
[Link]("Length of Content:"+l);
if(l==0)
{
[Link]("Content Not Available");
}
else{
int ch;
InputStream in= [Link]();
while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
}
}
}
OUTPUT:
import [Link].*;
import [Link].*;
public class GetIPAddress
{
public static void main(String[] args){
try{
InetAddress ip=[Link]("[Link]");
[Link]("Host Name: "+[Link]());
[Link]("IP Address: "+[Link]());
}
catch(Exception e){
[Link](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 =
[Link]() 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 [Link]
–[Link]
•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()
–
–[Link]
•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.
[Link]
import [Link].*;
import [Link].*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader([Link]));
Socket clientSocket = new Socket(“localhost", 6789);
DataOutputStream outToServer =
new DataOutputStream([Link]());
[Link]
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader([Link]()));
sentence = [Link]();
[Link](sentence + '\n');
modifiedSentence = [Link]();
[Link]("FROM SERVER: " + modifiedSentence);
[Link]();
}
}
[Link]
import [Link].*;
import [Link].*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new
ServerSocket(6789);
while(true) {
Socket connectionSocket =
[Link]();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader([Link]()));
[Link]
DataOutputStream outToClient =
new DataOutputStream([Link]());
clientSentence = [Link]();
capitalizedSentence = [Link]() + '\n';
[Link](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
[Link]
import [Link].*;
import [Link].*;
public class chatclient
{
public static void main(String args[]) throws Exception
{
Socket sk=new Socket("localhost",2000);
BufferedReader sin=new BufferedReader(new
InputStreamReader([Link]()));
PrintStream sout=new PrintStream([Link]());
BufferedReader stdin=new BufferedReader(new
InputStreamReader([Link]));
String s;
while ( true )
{
[Link]("Client : ");
s=[Link]();
[Link](s);
s=[Link]();
[Link]("Server : "+s+"\n");
if ( [Link]("BYE") )
break;
}
[Link]();
[Link]();
[Link]();
[Link]();
}
}
[Link]
import [Link].*;
import [Link].*;
public class chatserver {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(2000);
Socket sk=[Link]();
BufferedReader cin=new BufferedReader(new
InputStreamReader([Link]()));
PrintStream cout=new PrintStream([Link]());
BufferedReader stdin=new BufferedReader(new
InputStreamReader([Link]));
String s;
while ( true )
{ s=[Link]();
if ([Link](“BYE"))
{
[Link]("BYE"); break; }
System. [Link]("Client : "+s+"\n");
[Link]("Server : ");
s=[Link]();
[Link](s);
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link](); } }
[Link]
import [Link].*;
import [Link].*;
public class UDPClient
{
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 7777;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader([Link]));
try
{
sock = new DatagramSocket();
InetAddress host = [Link]("localhost");
while(true)
{
//take input and send the packet
echo("Enter message to send : ");
s = (String)[Link]();
byte[] b = [Link]();
DatagramPacket dp = new DatagramPacket(b , [Link] , host , port);
[Link](dp);
[Link]
//now receive reply
//buffer to receive incoming data
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, [Link]);
[Link](reply);
byte[] data = [Link]();
s = new String(data, 0, [Link]());
//echo the details of incoming data - client ip : client port - client message
echo([Link]().getHostAddress() + " : " + [Link]() + " - " + s);
}
}
catch(IOException e)
{
[Link]("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
[Link](msg);
}
}
[Link]
import [Link].*;
import [Link].*;
public class UDPClient
{
public static void main(String args[])
{
DatagramSocket sock = null;
int port = 7777;
String s;
BufferedReader cin = new BufferedReader(new InputStreamReader([Link]));
try
{
sock = new DatagramSocket();
InetAddress host = [Link]("localhost");
while(true)
{
//take input and send the packet
echo("Enter message to send : ");
s = (String)[Link]();
byte[] b = [Link]();
[Link]
DatagramPacket dp = new DatagramPacket(b , [Link] , host , port);
[Link](dp);
byte[] buffer = new byte[65536];
DatagramPacket reply = new DatagramPacket(buffer, [Link]);
[Link](reply);
byte[] data = [Link]();
s = new String(data, 0, [Link]());
//echo the details of incoming data - client ip : client port - client message
echo([Link]().getHostAddress() + " : " + [Link]() + " - " + s);
}
}
catch(IOException e)
{
[Link]("IOException " + e);
}
}
//simple function to echo data to terminal
public static void echo(String msg)
{
[Link](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, [Link]);
[Link](DpReceive);
[Link]("Client:-" + data(receive));
if (data(receive).toString().equals("bye"))
{
[Link]("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)
{
[Link]((char) a[i]);
i++;
}
return ret;
}
}
public class udpBaseClient_2
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner([Link]);
DatagramSocket ds = new DatagramSocket();
InetAddress ip = [Link]();
byte buf[] = null;
while (true)
{
String inp = [Link]();
buf = [Link]();
DatagramPacket DpSend =new DatagramPacket(buf, [Link], ip, 5551);
[Link](DpSend);
if ([Link]("bye"))
break;
}
}
}