Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

TCP Socket Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

TCP Socket Programming

User and System Programs

Kernel Support

Hardware

Ports
Used to address processes on a host 0-1024 is usually reserved for known service

FTP Web Server Server 21 80 Transport Layer Network Layer DLL/Physical


3

A port is a service provided by a machine.

That service is identified by a number. There are a lot of standardized port

numbers for popular services. Port 22 is


for FTP. Port 80 is for HTTP. There are many, many others.

What is a socket?
An abstract interface provided to the

application programmer

File descriptor, allows apps to read/write to the network

Allows to processes on remotely

connected computers to talk to each other

Socket
A socket is a communication path to a port.

When you want your program to communicate


over the network, you have given it a way of addressing the port and this is done by creating a socket and attaching it to the port.
Basically,

socket = IP + ports Sockets

provide access to the port + ip.


6

Sockets

Socket

are

sort

of

the

programming

interface from the programmer's side and the communications endpoint from the networking

side.
In the Internet case, a socket would have an IP

address and a port number. IP address and a port represent a unique reception point or transmission point in an operating system for it

to communicate to the outside world


7

Two types of sockets


SOCK_STREAM TCP connection oriented, bidirectional reliable, in-order delivery

SOCK_DGRAM

UDP

no connection
unreliable delivery, no guarantee on the order can send/receive

Socket-programming using TCP


Socket: a door between application process and endend-transport protocol (UDP or TCP) TCP service: reliable transfer of bytes from one process to another
controlled by application developer controlled by operating system

process socket TCP with buffers, variables

process socket TCP with buffers, variables

controlled by application developer controlled by operating system

internet

host or server

host or server
9

Socket programming with TCP


Client must contact server server process must first be running server must have created socket (door) that welcomes clients contact
Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP
When contacted by client,

server TCP creates new socket for server process to communicate with client allows server to talk with multiple clients source port numbers used to distinguish clients

application viewpoint

TCP provides reliable, in-order transfer of bytes (pipe) between client and server
10

Socket Programming in C

Socket Programming - Flow


socket()

socket()
bind() listen()

connect()

Client

send() recv()

Server
wait for connection request from next client

accept() recv()

. . .

send()
close()

close()

12

socket()
int s_listen = socket(family, type, protocol);

family: AF_INET specifies Ipv4 type: SOCK_STREAM, SOCK_DGRAM protocol: 0 (pseudo, IP ). See /etc/protocols

13

bind()
bind(s_listen, localAdd, addLength) Server specifies which port and address it will be listening to s_listen: our listening socket descriptor localAdd: socket address structure addLength: length of localAdd

14

Address Structure
struct sockaddr_in { u_char sin_len; // length of address u_char sin_family; // family of address u_short sin_port; // protocol port num struct in_addr sin_addr; // IP Addr char sin_zero[8]; // set to zero, used for padding };

15

Address Structure
Declare address structure

struct sockaddr_in sockAdd; Set family sockAdd.sin_family = AF_INET; Set IP address (2 ways) //specify address to listen to

inet_pton(AF_INET,127.0.0.1,&sockAdd.sin_addr.s_addr)

//listen to any local address sockAdd.sin_addr.s_addr = htonl(INADDR_ANY)


Set port

sockAdd.sin_port = htons(9999);

16

Difference between Client sockets & Server sockets


Server sockets are generally bound to well known

names

(ports)

and

they

establish

themselves

with listen(). You need to perform binding regardless of socket family for server sockets.
For client sockets it depends. For AF_INET type of

sockets underlying stack (TCP) performs binding for client sockets.


Client sockets establish themselves with connect().

17

listen()
Calling listen() on a socket causes the kernel's tcp/ip

implementation to begin accepting connections sent to the socket's bound name (port).
This will happen whether or not you ever call accept().

int status = listen(s_listen, queuelength);

status: -1 if error, 0 otherwise


s_listen: socket descriptor queuelength: Number of clients that can wait for a connection listen is non-blocking: returns immediately
18

accept()
accept() simply gives your server a way to access and

interact with the client sockets that have connected


to your listening socket.
int s_new = accept(s_listen, &clientAddress, &addLength);

s_new: new socket for communication with client s_listen: the listening socket clientAddress: struct sockaddr, address of client addLength: size of client address structure accept is blocking: waits for connection before returning

19

Talking
int send(int s_new, const void *buf, int len, int flags);

s_new socket descriptor buf pointer to buffer len size of buffer flags can be safely set to 0 int recv(int s_new, void *buf, int len, unsigned int flags); similar to send buf holds the data to be transferred

20

Concurrent Server
The key in understanding how the listening

socket continues to listen while the accepted connection is doing its thing is in understanding

that tcp connections depend on a 4-tuple of (1)


local address (2) local port (3) foreign address (4) foreign port.
These define a unique connection.

21

Before accept() passed back the new socket the

kernel used these values to create various structures so that in collaboration with the tcp/ip stack all traffic with this tuple will go to the connected socket.
Even though your server may have a thousand

connections with local address 192.168.1.100 port 80, the client combination of address and port will always be different and thus the tuple is always unique.
22

System calls - fork()


fork() is a C system call used to spawn child

processes

Execution for both child and parent process continues at the next instruction fork() returns
0 if this is the child process PID (>0) of the child process if this is the parent <0 if fork() fails

Used to keep listening on socket and talking

on another socket

23

24

Socket Programming in Java

Stream jargon
keyboard monitor

A stream is a sequence of

characters that flow into or out of a process. An input stream is attached to some input source for the process, e.g., keyboard or socket. An output stream is attached to an output source, e.g., monitor or socket.

Client Process process

input stream

inFromUser

output stream

inFromServer

outToServer

input stream

client TCP clientSocket socket


to network

TCP socket

from network

26

Example: Java client (TCP)


import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; Create input stream Create client socket, connect to server Create output stream attached to socket

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


Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
27

Example: Java client (TCP), cont.


Create input stream attached to socket

BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));


sentence = inFromUser.readLine();

Send line to server Read line from server

outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
28

Example: Java server (TCP)


import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence;

Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket

ServerSocket welcomeSocket = new ServerSocket(6789);


while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

29

Example: Java server (TCP), cont


Create output stream, attached to socket
Read in line from socket Write out line to socket } } DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';


outToClient.writeBytes(capitalizedSentence); }

End of while loop, loop back and wait for another client connection

30

Demo

A simple client server example: Echo Server

References
Socket Programming, Dan Rubinstein, http://www1.cs.columbia.edu/~danr/courses/6761/Fall00/intro/6761-1bsockets.ppt 15-441 Socket Programming, www.cs.cmu.edu/afs/cs/academic/class/15441f01/www/lectures/lecture03.ppt Network Programming, Geoff Kuenning, www.cs.hmc.edu/~geoff/classes/hmc.cs105.200701/slides/class21_net2.ppt Socket Programming, Abhinav Jain, www.cs.purdue.edu/homes/jain8/cs422/pso3.ppt

32

You might also like