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

Bcs Socket Programming

This document discusses network programming concepts like socket programming, client-server model, IP addresses, ports, TCP and UDP. It explains key socket functions like socket(), bind(), listen(), accept(), connect(), read(), write() and close() for creating client-server applications. It also covers concepts like sockets, socket addresses and TCP connection establishment. The fork() function is described for creating concurrent servers by spawning child processes.

Uploaded by

Sana Iftikhar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
163 views

Bcs Socket Programming

This document discusses network programming concepts like socket programming, client-server model, IP addresses, ports, TCP and UDP. It explains key socket functions like socket(), bind(), listen(), accept(), connect(), read(), write() and close() for creating client-server applications. It also covers concepts like sockets, socket addresses and TCP connection establishment. The fork() function is described for creating concurrent servers by spawning child processes.

Uploaded by

Sana Iftikhar
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

NETWORK PROGRAMMING

Speaker: Junaid Tariq, Lecturer, Department of Computer Science

INTRODUCTION

Socket Programming

socket programming or clientserver programming, involves writing computer programs that communicate with other programs across a computer network.

INTRODUCTION

Client / Server

Client

Communication link

Server

Figure 1.1 Network application : client and server

Client ...
Client ... Client
Figure 1.2 Server handling multiple clients at the same time.
4

Server

CLIENT - SERVER

A server is a process - not a machine ! A server waits for a request from a client.

A client is a process that sends a request to an existing server and (usually) waits for a reply.

IP ADDRESS

An Internet Protocol address (IP address) is a numerical label that is assigned to any device participating in a computer network that uses the Internet Protocol for communication between its nodes.

IPv4 (32 bit-4bytes) IPv6 (128 bit-16bytes)

PORT

In computer networking, a port is an application-specific or process-specific software construct serving as a communications endpoint. Port number size 16-bits

PORT NUMBERS

TCP / UDP use 16bit port number. 65536 (1-65535) Clients use ephemeral ports, that is, short lived ports. The port numbers are divided into three ranges:

The : 0 through 1023. These port numbers are controlled and assigned by the IANA (Internet Assigned Numbers Authority). For example, port 80 is assigned for a Web server. The : 1024 through 49151. These are not controlled by the IANA, but the IANA registers and lists the uses of these ports as a convenience to the community. For example, ports 6000 through 6063 are assigned for an X Window server for both protocols (TCP/ UDP), even though all implementations currently use only TCP.

The , 49152 through 65535. The IANA says nothing about these ports. These are what we call ephemeral ports. (The magic number 49152 is three-fourths of 65536.)

INTRODUCTION

Socket

Socket = IP address + TCP or UDP port number.


The two values that identify each endpoint, an IP address and a port number, are often called a .

IPV4 SOCKET ADDRESS


struct in_addr{ in_addr_t }; s_addr;

STRUCTURE
/*32bit IPv4 address*/ /*network byte ordered*/

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]; }; /* included in <netinet/in.h> */

/* length of structure(16) */ /* AF_INET */ /* 16bit TCP or UDP port number */ /*network byte ordered*/ /* 32bit IPv4 address */ /*network byte ordered*/ /* unused */

SOCKET PAIR

The socket pair for a TCP connection is the four-tuple that defines the two endpoints of the connection:

The local IP address, local port, foreign IP address, and foreign port.

A uniquely identifies every TCP connection on a network.

11

TCP CONNECTION
socket
connect

socket bind listen

client
write

server
accept read

read close

write close
12

SOCKET FUNCTIONS
TCP Server

socket()
Well known port TCP Client

bind() listen()

socket()
3WHS

accept()
Blocks until connection from client Data Data End of Data Indication

connect()
write()

read()

read()
close()

write()
read()
13

close()

CLIENT-SERVER CONNECTION
Talk to mail.yahoo.com, mail.yahoo.com my-machine port b

I am mail.yahoo.com, port b

I accept connections client server I will talk to my-machine, port a

Resulting TCP connection identified by (my-machine:a, mail.yahoo.com:b)

14

CLIENT-SERVER CONNECTION
Talk to mail.yahoo.com, mail.yahoo.com my-machine port b 4. socket() 5. connect() client 7. write() / sendto() 8. read() / rcvfrom() 9. close() / shutdown() server 6. accept()

I am mail.yahoo.com, port b 1. socket() 2. bind()


I accept connections 3. listen()

I will talk to my-machine, port a

15

SOCKETS: CONCEPTUAL VIEW

16

SOCKET CREATION
17

CREATING SOCKETS - SOCKET()


int socket (int family, int type, int protocol); Create a socket. Returns file descriptor or -1. Also sets errno on failure. family: address family (namespace) or protocol family

AF_INET for IPv4 other possibilities: AF_INET6 (IPv6), AF_UNIX, AF_OSI or AF_LOCAL (Unix socket), AF_ROUTE (routing) SOCK_STREAM for TCP (with AF_INET) SOCK_DGRAM for UDP (with AF_INET) Usually already defined by domain & type, typically 0 (default)
18

type: style of communication


protocol: protocol within family

NAMING AND IDENTIFYING SOCKETS - BIND()


int bind (int sockfd, struct sockaddr* myaddr, int addrlen); Bind a socket to a local IP address and port number. Returns 0 on success, -1 and sets errno on failure.

sockfd: socket file descriptor (returned from socket) myaddr: includes IP address and port number

IP address: set by kernel if value passed is INADDR_ANY, else set by caller port number: set by kernel if value passed is 0, else set by caller
19

addrlen: length of address structure = sizeof (struct sockaddr_in)

WAITING FOR CONNECTIONS - LISTEN()


int listen (int sockfd, int backlog); Put socket into passive state (wait for connections rather than initiate a connection). Returns 0 on success, -1 and sets errno on failure. sockfd : socket file descriptor (returned from socket ) backlog : bound on length of unaccepted connection queue (connection backlog); kernel will cap, thus better to set high
20

CONTACT THE PEER - CONNECT()


int connect (int sockfd, struct sockaddr* servaddr, int addrlen); Connect to another socket. Returns 0 on success, -1 and sets errno on failure.

sockfd : socket file descriptor (returned from socket ) servaddr : IP address and port number of server addrlen : length of address structure = sizeof (struct sockaddr_in)
Can use with UDP to restrict incoming datagrams and to obtain asynchronous errors.

21

WELCOME A CONNECTION - ACCEPT()


int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Accept a new connection (first one off queue of pending connections). Returns file descriptor or -1. Also sets errno. sockfd : socket file descriptor (returned from socket ) cliaddr : IP address and port number of client (returned from call) addrlen : length of address structure = pointer to int set to sizeof (struct sockaddr_in)

addrlen is a value-result argument: the caller passes the size of the address structure, the kernel returns the size of the22 clients address (the number of bytes written)

SENDING AND RECEIVING DATA

23

SEND THE DATA - WRITE()


int write (int sockfd, char* buf, size_t nbytes); Write data to a stream (TCP) or connected datagram (UDP) socket. Returns number of bytes written or -1. Also sets errno on failure.

sockfd : socket file descriptor (returned from socket ) buf : data buffer nbytes : number of bytes to try to write some reasons for failure or partial writes:

process received interrupt or signal kernel resources unavailable (e.g., buffers)

24

RECEIVE THE DATA - READ()


int read (int sockfd, char* buf, size_t nbytes); Read data from a stream (TCP) or connected datagram (UDP) socket. Returns number of bytes read or -1. Also sets errno on failure. sockfd : socket file descriptor (returned from socket ) buf : data buffer nbytes : number of bytes to try to read Returns 0 if socket closed.

25

TEARING DOWN A CONNECTION

26

GOOD BYE - CLOSE()


int close (int sockfd); Closes a socket and deletes descriptor from system tables. Returns 0 on success, -1 and sets errno on failure. sockfd : socket file descriptor (returned from socket ) Closes communication on socket in both directions. All data sent before close are delivered to other side (although this aspect can be overridden). After close() , sockfd is not valid for reading or writing.

27

CLOSE IN MY WAY - SHUTDOWN()


int shutdown (int sockfd, int howto); Force termination of communication across a socket in one or both directions. Returns 0 on success, -1 and sets errno on failure. sockfd : socket file descriptor (returned from socket ) howto :

SHUT_RD to stop reading SHUT_WR to stop writing SHUT_RDWR to stop both

shutdown() overrides the usual rules regarding duplicated sockets, in which TCP teardown does not occur until all copies have closed the socket.

28

COMMAND LINE ARGUMENT


#include<stdio.h> int main(int argc, char * argv[]) { int i; for(i=0;i<argc;i++) { printf("%s",argv[i]); printf("\n"); } return 0; }

Header File
Command line arguments Socket Creation
Specify Server address & port Establish Connection Read and Display

Bind Listening Socket Accept Connection

FORK AND EXEC FUNCTION


#include <unistd.h> pid_t fork(void);
Returns: 0 in child, process ID of child in parent, -1 on error

Before describing how to write a concurrent server, we must describe the Unix fork function. This function is the only way in Unix to create a new process. The hard part in understanding fork is that it is called once but it returns twice.

FORK CONT.

It returns once in the calling process (parent) with a return value that is the process ID of the newly created process (child). It also returns once in the child, with a return value of 0. Hence, the return value tells the process whether it is the parent or the child. The reason fork returns 0 in the child, instead of the parent's process ID, is because a child has only one parent and it can always obtain the parent's process ID by calling getppid. A parent, on the other hand, can have any number of children, and there is no way to obtain the process IDs of its children. If a parent wants to keep track of the process IDs of all its children, it must record the return values from fork.

FORK CONT.

All descriptors open in the parent before the call to fork are shared with the child after fork returns. There are two typical uses of fork:
1.

2.

A process makes a copy of itself so that one copy can handle one operation while the other copy does another task. A process wants to execute another program. Since the only way to create a new process is by calling fork, the process first calls fork to make a copy of itself, and then one of the copies calls exec to replace itself with the new program.

35

37

38

You might also like