Ipv4 Socket Address Structure struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */ }; struct sockaddr_in { uint8_t sin_len;

Slides:



Advertisements
Similar presentations
Network Programming Week #1 J.P. Yoo
Advertisements

Socket Programming Computer Networks, Spring 2008 Your TAs.
Echo server The client reads a line of text from its standard input and writes the line to the server The server reads the line from its network input.
Socket Programming 101 Vivek Ramachandran.
Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Socket Programming CS3320 Fall 2010.
MERANCANG Program Transfer File (PTF) PTFServer dan PTFClient I Made Astawa
IPv6 Technologies and Advanced Services page 1 Porting applications to IPv6 OpenH323 and IPv6 support K. Stamos Computer Engineer, University of Patras.
CSE 333 – SECTION 8 Networking and sockets. Overview Network Sockets IP addresses and IP address structures in C/C++ DNS – Resolving DNS names Demos.
Taekyung Kim 0x410 ~ 0x International Standards Organization (ISO) is a multinational body dedicated to worldwide agreement on international.
Programming with UDP – I Covered Subjects: IPv4 Socket Address Structure Byte Ordering Functions Address Access/Conversion Functions Functions: 1.socket()
CS252: Systems Programming Ninghui Li Based on slides by Prof. Gustavo Rodriguez-Rivera Topic 16: Socket Programming & Project 5.
Elementary TCP Sockets Computer Networks Computer Networks Term B10 UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Sockets Programming Introduction © Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid.
Tutorial 8 Socket Programming
CS 311 – Lecture 19 Outline Internet Sockets – gethostname utility – struct hostent – inet_addr – Machine byte to Network byte order translation and vice.
Programming with Berkeley Sockets Presented by Chris GauthierDickey Written by Daniel Stutzbach (I think!) for CIS 432/532 Useful References: ● man pages.
#include DatatypeDescription int8_t uint8_t int16_t uint16_t int32_t uint32_t Signed 8-bit integer Unsigned 8-bit integer Signed 16-bit integer Unsigned.
Introduction to Socket Programming April What is a socket? An interface between application and network –The application creates a socket –The socket.
Unix Network Programming Part 2: Elementary Sockets Jani Peusaari.
Introduction to Project 1 Web Client and Server Jan 2006.
Lecture 10 Overview. Network API Application Programming Interface – Services that provide the interface between application and protocol software often.
Sockets COS 518: Advanced Computer Systems Michael Freedman Fall
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
Client Software Design Objectives: Understand principles of C/S design, with focus on clients Review Windows implementations of Socket functions.
Basic Socket Programming TCP/IP overview. TCP interface Reference: –UNIX Network Programming, by Richard Stevens. –UNIX man page.
UNIX Socket Programming CS 6378
ECE453 – Introduction to Computer Networks Lecture 15 – Transport Layer (II)
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Socket Programming. Introduction Sockets are a protocol independent method of creating a connection between processes. Sockets can be either – Connection.
Sirak Kaewjamnong Computer Network Systems
 Wind River Systems, Inc Chapter - 13 Network Programming.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
Introduction to Socket
Sockets Introduction Socket address structures Value-result arguments
Introduction to Sockets
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
2: Application Layer 1 Socket Programming UNIX Network Programming, Socket Programming Tutorial:
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
回到第一頁 Client/sever model n Client asks (request) – server provides (response) n Typically: single server - multiple clients n The server does not need.
1 Network Programming. 2 Background Important guidelines –Use conductor.tamucc.edu or any LINUX machine to develop your network applications –Do not use.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
1 TCP Sockets Programming Creating a passive mode (server) socket.Creating a passive mode (server) socket. Establishing an application-level connection.Establishing.
Lecture 15 Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Lecture 3 TCP and UDP Sockets CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
Sockets Intro to Network Programming. Before the internet... Early computers were entirely isolated No Internet No network No model No external communications.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
Read: Chapters 1,2, 3, 4 Communications Client Server Ex: TCP/IP
UNIX Sockets COS 461 Precept 1.
Advanced Computer Networks
Network Programming CSC- 341
Socket Programming (Cont.)
Network Programming CSC- 341
Chapter4 Elementary TCP Socket
Socket Programming in C
Network Programming with Sockets
Tutorial on Socket Programming
Chapter 3 Sockets Introduction
תקשורת ומחשוב תרגול 3-5 סוקטים ב-C.
Socket Programming in C
TCP Sockets Programming
Advanced Network Programming spring 2007
Socket Programming.
Socket Programming(1/2)
Sockets Programming Socket to me!.
Sockets Programming Socket to me!.
Presentation transcript:

Ipv4 Socket Address Structure struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */ }; struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */ sa_family_t sin_family; /* AF_INET */ in_port_t sin_port; /* 16-bit TCP/UDP port number */ /* network byte ordered */ struct in_addr sin_addr; /* 32-bit IPv4 address */ /*network byte ordered*/ char sin_zero[8]; /* unused */ }; data structure – not exchanged between hosts

struct in_addr { in_addr_t s_addr; /* 32-bit IPv4 address */ /* network byte ordered */ }; struct sockaddr_in { uint8_t sin_len; /* length of structure (16) */ sa_family_t sin_family; /* AF_INET */ in_port_t sin_port; /* 16-bit TCP/UDP port number */ /* network byte ordered */ struct in_addr sin_addr; /* 32-bit IPv4 address */ /*network byte ordered*/ char sin_zero[8]; /* unused */ }; Generic Socket Address Structure Passed as reference Prior to void definition

Generic Socket Address Structure int bind(int, struct sockaddr *, sock_len_t);

Ipv6 Socket Address Structure struct in6_addr { uint8_t s6_addr[16]; /* 128-bit IPv6 address */ /* network byte ordered */ }; #define SIN6_LEN /* required for compile-time tests */ struct sockaddr_in6 { uint8_t sin6_len; /* length of this struct (28) */ sa_family_t sin6_family; /* AF_INET6 */ in_port_t sin6_port; /* transport layer port# */ /* network byte ordered */ uint32_t sin6_flowinfo; /* flow information, undefined */ struct in6_addr sin6_addr; /* IPv6 address */ /* network byte ordered */ uint32_t sin6_scope_id; /* set of interfaces for a scope */ };

Value-Results arguments bind, connect, sento

Value-Result arguments Kernel to the process, size can change accept, recvfrom, getsockname, getpeername Fixed size data structure Kernel informs how much information was stored

Socket Address Structures

Byte ordering functions

Internet Protocols Network byte order → big-endian  TCP Port: 16 bits  Ipv4 address: 32 bits # include uint16_t htons(uint16_t host16bitvalue) ; uint32_t htonl(uint32_t host32bitvalue) ; Both return: value in network byte order uint16_t ntohs(uint16_t net16bitvalue) ; uint32_t ntohl(uint32_t net32bitvalue) ; Both return: value in host byte order

Byte manipulation function Operates on multibyte fileds, without interpreting the data, and without asuming that the data is a null-terminated C string bzero, bcopy, bcmp memset, memcpy, memcmp

Address convertion function Converts an ASCII string into network byte ordered binary values #include int inet_aton(const char *strptr, struct in_addr *addrptr); Returns: 1 if string was valid, 0 on error in_addr_t inet_addr(const char *strptr); Returns: 32-bit binary network byte ordered IPv4 address; INADDR_NONE if error char *inet_ntoa(struct in_addr inaddr); Returns: pointer to dotted-decimal string

Address convertion function

read, write It may read/write less than needed due to finite buffer → call function Only if write is nonblocking

read, write lib/readn.c 1 #include "unp.h" 2 ssize_t /* Read "n" bytes from a descriptor. */ 3 readn(int fd, void *vptr, size_t n) 4 { 5 size_t nleft; 6 ssize_t nread; 7 char *ptr; 8 ptr = vptr; 9 nleft = n; 10 while (nleft > 0) { 11 if ( (nread = read(fd, ptr, nleft)) < 0) { 12 if (errno == EINTR) 13 nread = 0; /* and call read() again */ 14 else 15 return (-1); 16 } else if (nread == 0) 17 break; /* EOF */ 18 nleft -= nread; 19 ptr += nread; 20 } 21 return (n - nleft); /* return >= 0 */ 22 }

read, write lib/writen.c 1 #include "unp.h" 2 ssize_t /* Write "n" bytes to a descriptor. */ 3 writen(int fd, const void *vptr, size_t n) 4 { 5size_t nleft; 6 ssize_t nwritten; 7 const char *ptr; 8 ptr = vptr; 9 nleft = n; 10 while (nleft > 0) { 11 if ( (nwritten = write(fd, ptr, nleft)) <= 0) { 12 if (nwritten < 0 && errno == EINTR) 13 nwritten = 0; /* and call write() again */ 14 else 15 return (-1);/* error */ 16 } 17 nleft -= nwritten; 18 ptr += nwritten; 19 } 20 return (n); 21 }

read, write 1 # include "unp.h" 2 static int read_cnt; 3 static char *read_ptr; 4 static char read_buf[MAXLINE]; 5 static ssize_t 6 my_read(int fd, char *ptr) 7 { 8 if (read_cnt <= 0) { 9 again: 10 if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) { 11 if (errno == EINTR) 12 goto again; 13 return (-1); 14 } else if (read_cnt == 0) 15 return (0); 16 read_ptr = read_buf; 17 } 18 read_cnt--; 19 *ptr = *read_ptr++; 20 return (1); 21 }

22 ssize_t 23 readline(int fd, void *vptr, size_t maxlen) 24 { 25 ssize_t n, rc; 26 char c, *ptr; 27 ptr = vptr; 28 for (n = 1; n < maxlen; n++) { 29 if ( (rc = my_read(fd, &c)) == 1) { 30 *ptr++ = c; 31 if (c == '\n') 32 break; /* newline is stored, like fgets() */ 33 } else if (rc == 0) { 34 *ptr = 0; 35 return (n - 1); /* EOF, n - 1 bytes were read */ 36 } else 37 return (-1); /* error, errno set by read() */ 38 } 39 *ptr = 0; /* null terminate like fgets() */ 40 return (n); 41 } 42 ssize_t 43 readlinebuf(void **vptrptr) 44 { 45 if (read_cnt) 46 *vptrptr = read_ptr; 47 return (read_cnt); 48 } read, write

isfdtype It checks whether the descriptor is a socket descriptor

Socket functions for elementary TCP client-server

The socket API Function socket int socket ( int family, int type, int protocol) return > 0 if OK, -1 if error Returns socket descriptor (small positive integer), similar to UNIX file descriptor, to be used perform functions on the socket such as read, write and close

socket #include int socket (int family, int type, int protocol); Returns: non-negative descriptor if OK, -1 on error

Socket Function Parameters: family: specifies the protocol family: AF_INET – for IPv4 AF_INET6 – for IPv6 AF_UNIX ou AF_LOCAL- Unix domain socket type : specifies transport protocol: SOCK_STREAM: stream socket for TCP SOCK_DGRAM: datagram socket for UDP protocol : usually set to zero

Combination of interest Family Type AF_INETSOCK_STREAMSOCK_DGRAM AF_UNIXSOCK_STREAMSOCK_DGRAM Exemple: sockfd = socket(AF_INET, SOCK_STREAM, 0), creates an IPv4 socket to be used by TCP socket Function

int connect ( int sockfd, const struct sockaddr *servaddr, int addrlen) return 0 if OK, -1 if error, Used for establishing a connection:three-way handshake sockfd : return parameter of socket() servaddr : data structure initiated with remote socket identifications (remote IP address, remote port number) For a client TCP, it is not necessary to perform bind: the kernel chooses the local port ephemeral port number and the source IP number if necessary Chosen in a way to avoid conflict of use of port number Connect Function

connect errors  timeout – erro ETIMEDOUT, 75 seconds, configurable  If the answer to a SYN segment is an RST one – error ECONNREFUSED – no process listening to the port  Destination unreachable (ICMP), soft error, tries for 75 seconds (4.4 BSD) #include int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen); Returns: 0 if OK, -1 on error

int bind(int sockfd, (struct sockaddr)* myaddr, int socklen) return 0 if OK, -1 if error  bind a local protocol address given by the structure myaddr to a socket ( sockfd)  The application can let the kernel chooses the IP address and the port number; Bind Function

If a host has more than one IP, then the kernel can choose one Ephemeral port numbers are chosen to avoid conflict with other socket To let the kernel chooses the IP address the constant INADDR_ANY should be assigned to the IP address myaddr To let the kernel chooses an ephemeral port number the constant zero should be set to the corresponding field of myaddr: *myaddr.sin_port = 0; *myaddr.sin_addr.s_addr = INADDR_ANY

bind Bind performed by TCP server restricts the socket to receiving incoming client connection destined only to that IP address #include int bind (int sockfd, const struct sockaddr *myaddr, socklen_t addrlen); Returns: 0 if OK, -1 on error

bind No cliente, kernel faz o bind com o endereço IP da interface

Listen Function An active (client) socket is one that called connect com o socket, starting a 3-way handshake with a remote host; An applications (server) which calls listen, makes an unconnected socket a passive one meaning that the kernel must accept incoming connection requests directed to this socket. CLOSED → LISTEN Clients call connect while servers call listen followed by accept The backlog parameter indicates the total size of two queues: the complete queue (ESTABLISHED state) and the incomplete connection queue (SYN_RVCD state) int listen (int sockfd, (struct sockaddr) * myaddr, int backlog) return 0 if OK, -1 if error

listen

accept Function Called by a TCP server to return the next completed connection from the front of the completed connection queue. If the queue is empty the process is oput to sleep int accept (int sockfd, (struct sockaddr) * cliaddr, int * socklen) returns nonnegative descriptor if OK, -1 if error  aadrlen is a value-result argument and it returns the size of the structure pointed to by cliaddr, i.e., the number of bytes stored by the kernel in the socket address structure.

fork - exec Fork is called once but it returns twice. The return value tell the process whether it is a parent or a child It returns once to the calling process (parent) with a return value that is the process ID of the newly created process (child) It returns once in the child, with a return value of zero (0) All the descriptors opened by the parent before the fork are shared with the child after the fork. connected sockts aer an accept and a fork is shared with the Two uses of fork: a process makes a copy of itself (fork) and a process executes another program ( fork e exec ) # include pid_t fork(void); Returns: 0 in child, process ID of child in parent, -1 on error

fork - exec #include int execl (const char *pathname, const char *arg0,... /* (char *) 0 */ ); int execv (const char *pathname, char *const argv[ ]); int execle (const char *pathname, const char *arg0,... /* (char *) 0, char *const envp[ ] */ ); int execve (const char *pathname, char *const argv[ ], char *const envp[ ]); int execlp (const char *filename, const char *arg0,... /* (char *) 0 */ ); int execvp (const char *filename, char *const argv[ ]); All six return: -1 on error, no return on success

fork - exec

Concurrent server Concurrent server (iterative server) – one server, several connections. Concurrent server serves several active connections. Server performers a fork to create a child to handle the client request After accept, the server calls fork and the child serves the client (on connfd, the connected socket) and the parent waits for another connection (on listenfd, the listening socket)

Concurrent server Connect returns a brand new socket descriptor for the connection to be established with the TCP client. The return of a connect makes a socket a connected socket. On closing a socket only the specific connection (socket) is closed, the server remains listening to new socket connection request

Concurrent server A close performed by the server does not imply in terminating the connection, a FYN is sent only when the number of reference to the descriptor in the file table is zero – when a child is created the number of reference is incremented by one. If a server does not close the socket none of the children connections will be closed since the number of reference will never be zero and server runs out of descriptor

Concurrent server pid_t pid; int listenfd, connfd; listenfd = Socket(... ); /* fill in sockaddr_in{ } with server's well-known port */ Bind(listenfd,... ); Listen(listenfd, LISTENQ); for ( ; ; ) { connfd = Accept (listenfd,... ); /* probably blocks */ if( (pid = Fork()) == 0) { Close(listenfd); /* child closes listening socket */ doit(connfd); /* process the request */ Close(connfd); /* done with this client */ exit(0); /* child terminates */ } Close(connfd); /* parent closes connected socket */ }

Concurrent server

close SHUTDOWN used instead to force the termination of a connection #include int close (int sockfd); Returns: 0 if OK, -1 on error

getsockname and getpeername Returns the protocol address either local or remote usos:  connect not followed by bind  After calling bind with 0 srgument  TCP server performs a bind in a wildcard port #include int getsockname(int sockfd, struct sockaddr *localaddr, socklen_t *addrlen); int getpeername(int sockfd, struct sockaddr *peeraddr, socklen_t *addrlen); Returns: 0 if OK, -1 on error

getsocketname and getpeername lib/sockfd_to_family.c 1 #include "unp.h" 2 int 3 sockfd_to_family(int sockfd) 4 { 5 struct sockaddr_storage ss; 6 socklen_t len; 7 len = sizeof(ss); 8 if (getsockname(sockfd, (SA *) &ss, &len) < 0) 9 return (-1); 10 return (ss.ss_family); 11 }

TCP ports and concurrent servers multihomed – one-or-any any-wildcard

TCP ports and concurrent servers