SlideShare a Scribd company logo
Network Programming with Sockets Reading:  Stevens 3rd ed., Ch. 3-6, or 2 nd  ed. Beej's Guide to Network Programming http://beej.us/guide/bgnet/
Outline Basic socket programming Concurrent communication Libnet and libcap library
Sockets process sends/receives messages to/from its  socket socket analogous to door sending process shoves message out door sending process relies on transport infrastructure on other side of door which brings message to socket at receiving process Internet controlled by app developer process TCP with buffers, variables socket host or server process TCP with buffers, variables socket host or server
Client-Server Model Asymmetric Communication Client sends requests Server sends replies Server/Daemon Well-known name (e.g., IP address + port) Waits for contact Processes requests, sends replies Client Initiates contact Waits for response Client Server Client Client Client
Client-Server Communication Model Service Model Concurrent: Server processes multiple clients’ requests simultaneously Sequential: Server processes only one client’s requests at a time Hybrid: Server maintains multiple connections, but processes responses sequentially Client and server categories are not disjoint A server can be a client of another server A server can be a client at the same time Example?
TCP Service Reliable Data Transfer Guarantees delivery of all data Exactly once if no catastrophic failures  Ordered Data Transfer Guarantees in-order delivery of data If A sends M1 followed by M2 to B, B never receives M2 before M1 Regulated Data Flow Monitors network and adjusts transmission appropriately Prevents senders from wasting bandwidth Reduces global congestion problems Data Transmission Full-Duplex byte stream Connection setup and teardown
UDP Services User Datagram Protocol Service Provides a thin layer over IP 16-bit port space (distinct from TCP ports) allows multiple recipients on a single host
UDP Services Unit of Transfer Datagram (variable length packet) Unreliable No guaranteed delivery Drops packets silently Unordered No guarantee of maintained order of delivery Unlimited Transmission No flow control
Byte Ordering Big Endian vs. Little Endian Little Endian (Intel, DEC): Least significant byte of word is stored in the lowest memory address Big Endian (Sun, SGI, HP): Most significant byte of word is stored in the lowest memory address Network Byte Order = Big Endian Allows both sides to communicate  Must be used for some data (i.e. IP Addresses) Good form for all binary data Most significant Byte 0xAA Least significant Byte   0xBB Least significant Byte   0xBB Most significant Byte   0xAA 0x1000 0x1001 Big-Endian (Network-Byte-Order) Little-Endian Memory address
Byte Ordering Functions 16- and 32-bit conversion functions (for platform independence) Examples: int m, n; short int s,t; m = ntohl (n)  net-to-host long (32-bit) translation s = ntohs (t)  net-to-host short (16-bit) translation n = htonl (m)  host-to-net long (32-bit) translation t = htons (s)  host-to-net short (16-bit) translation
BSD Sockets BSD Sockets PF_INET sockets PF_PACKET  Socket PF_NETLINK  Socket TCP UDP IP Network device SOCK_ STREAM SOCK_ DGRAM SOCK_ RAW
BSD Socket Structure include/linux/net.h struct socket { socket_state  state;/* SS_CONNECTED .. */ unsigned long  flags; struct proto_ops  *ops;/*protocols do most everything*/ struct fasync_struct  *fasync_list; struct file  *file; struct sock  *sk; /*hold protocol specific info*/ wait_queue_head_t  wait; short  type;/*SOCKET_STREAM */  unsigned char  passcred; }; struct sock { … struct sk_buff_head  sk_receive_queue; struct sk_buff_head  sk_write_queue; }
struct proto_ops { int  family; struct module  *owner; int  (*release)  (struct socket *sock); int  (*bind)  (struct socket *sock, struct sockaddr *myaddr, int sockaddr_len); int  (*connect)  (struct socket *sock, struct sockaddr *vaddr, int sockaddr_len, int flags); int  (*socketpair)(struct socket *sock1, struct socket *sock2); int  (*accept)  (struct socket *sock, struct socket *newsock, int flags); int  (*getname)  (struct socket *sock, struct sockaddr *addr, int *sockaddr_len, int peer); unsigned int  (*poll)  (struct file *file, struct socket *sock, struct poll_table_struct *wait); int  (*ioctl)  (struct socket *sock, unsigned int cmd, unsigned long arg); int  (*listen)  (struct socket *sock, int len); int  (*shutdown)  (struct socket *sock, int flags); int  (*setsockopt)(struct socket *sock, int level, int optname, char __user *optval, int optlen); int  (*getsockopt)(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen); int  (*sendmsg)  (struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len); int  (*recvmsg)  (struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags); … };
Socket Address Structure Socket address struct sockaddr { short sa_family;  char sa_data[14];  }; Internet address:  struct sockaddr_in { short sin_family;    /* e.g., AF_INET */ ushort sin_port;    /* TCP/UDP port */ struct in_addr sin_addr;    /* IP address */ unsigned char  sin_zero[8]; /* Same size as struct sockaddr */ }; IP address: struct in_addr { in_addr_t s_addr;    /* 32-bit IP address */ }; all but sin_family in network byte order
Address Access/Conversion Functions All binary values are network byte ordered struct hostent* gethostbyname (const char* hostname); Translate English host name to IP address (uses DNS) struct hostent* gethostbyaddr (const char* addr, size_t len, int family); Translate IP address to English host name (not secure) Better used in combination of gethostbyname() to validate the results char* inet_ntoa (struct in_addr inaddr); Translate IP address to ASCII dotted-decimal notation (e.g., “128.32.36.37”) int gethostname (char* name, size_t namelen); Read host’s name (use with gethostbyname to find local IP) (/etc/hosts)
Structure: hostent The  hostent   data structure (from  /usr/include/netdb. h ) canonical domain name and aliases list of addresses associated with machine also address type and length information struct hostent { char* h_name;  /* official name of host */ char** h_aliases;  /* NULL-terminated alias list */ int h_addrtype  /* address type (AF_INET) */ int h_length;  /* length of addresses (4B) */ char** h_addr_list; /* NULL-terminated address list */ #define h_addr h_addr_list[0];/* backward-compatibility */ };
Address Access/Conversion Functions in_addr_t inet_addr (const char* strptr); Translate dotted-decimal notation to IP address (Network Byte Order);  returns -1 on failure, thus cannot handle broadcast value  “255.255.255.255” struct sockaddr_in ina; ina.sin_addr.s_addr = inet_addr("10.12.110.57"); int inet_aton (const char *strptr, struct in_addr *inaddr); Translate dotted-decimal notation to IP address; returns 1 on success, 0 on failure struct sockaddr_in my_addr; my_addr.sin_family = AF_INET;  // host byte order my_addr.sin_port = htons(MYPORT);  // short, network byte order inet_aton("10.12.110.57",&(my_addr.sin_addr)); memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct
Sockets API Creation and Setup Establishing a Connection (TCP) Sending and Receiving Data Tearing Down a Connection (TCP)
Socket Functions blocks until connection  from client TCP Client TCP Server socket() listen() accept() socket() bind() Well-known port connect() write() TCP three-way handshaking data (request) read() process request
Socket Functions blocks until connection  from client TCP Server TCP Client read() data (reply) close() read() close() socket() connect() write() TCP three-way handshaking data (request) read() process request write()
Socket Creation and Setup Include file   <sys/socket.h> Create a socket int socket (int domain, int type, int protocol); Returns file descriptor or -1. Bind a socket to a local IP address and port number int bind (int sockfd, struct sockaddr* myaddr, int addrlen); Put socket into passive state (wait for connections rather than initiate a connection). int listen (int sockfd, int backlog); Accept connections int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Returns file descriptor or -1.
Functions: socket int socket (int domain, int type, int protocol); Create a socket.  Returns file descriptor or -1. Also sets  errno   on failure. domain : protocol family (same as address family) PF_INET  for IPv4 other possibilities:  PF_INET6  (IPv6),  PF_UNIX  or  PF_LOCAL  (Unix socket),  PF_ROUTE  (routing) type : style of communication SOCK_STREAM  for TCP (with  PF_INET ) SOCK_DGRAM  for UDP (with  PF_INET ) protocol : protocol within family typically 0 getprotobyname(), /etc/protocols for list of protocols
Function: 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 addrlen : length of address structure = sizeof (struct sockaddr_in) socket.socket_state = TCP_CLOSE;
TCP and UDP Ports Allocated and assigned by the Internet Assigned Numbers Authority  see  RFC 1700  or ftp://ftp.isi.edu/in-notes/iana/assignments/port-numbers private/ephemeral ports 49152-65535 registered services/ephemeral ports 1024-49151 registered and controlled, also used for identity verification super-user only 513-1023 standard services (see  /etc/services ) super-user only 1-512
Functions: 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 socket.socket_state = TCP_LISTEN;
Functions: accept int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Accept a new connection.  Returns file descriptor or -1. Also sets  errno   on failure. 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 the client’s address (the number of bytes written)
Accept (cont'd) A new socket was cloned from the listening socket If there are no incoming connection to accept Non-Blocking—accept operation failed and throw away the new socket Blocking—accept operation was added to the wait queue (default)
TCP Connection Setup client server socket socket connect bind listen accept connect completes connection added to incomplete queue connection moved to complete queue Synchronize (SYN) J SYN K,  acknowledge (ACK) J+1 ACK K+1
server #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #define PORT 3490  #define BACKLOG 10  /* how many pending   connections queue    will hold */
server main() { int sockfd, new_fd; /* listen on sock_fd, new    connection on new_fd */ struct sockaddr_in my_addr;  /* my address */ struct sockaddr_in their_addr; /* connector addr */ int sin_size; if ((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){ perror(&quot;socket&quot;); exit(1); }
server my_addr.sin_family = AF_INET;  /* host byte order */ my_addr.sin_port = htons(MYPORT); /* short, network      byte order */ my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* INADDR_ANY allows clients to connect to any one of the host’s IP address */ bzero(&(my_addr.sin_zero), 8); /* zero the struct */ if (bind(sockfd, (struct sockaddr *)&my_addr,   sizeof(struct sockaddr)) == -1) { perror(&quot;bind&quot;); exit(1); }
server if (listen(sockfd, BACKLOG) == -1) { perror(&quot;listen&quot;); exit(1); } while(1) { /* main accept() loop */ sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr*)   &their_addr,&sin_size)) == -1) { perror(&quot;accept&quot;); continue; } printf(&quot;server: got connection from %s\n&quot;, inet_ntoa(their_addr.sin_addr));
Establishing a Connection Include file   <sys/socket.h> 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)
Connect Before connecting,  socket.socket_state = SS_UNCONNECTED; Add the sock to tcp_listening_hash waiting for server’s response
client if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit (1); } their_addr.sin_family = AF_INET; /* interp’d by host */ their_addr.sin_port = htons (PORT); their_addr.sin_addr = *((struct in_addr*)he->h_addr); bzero (&(their_addr.sin_zero), 8); /* zero rest of struct */ if (connect (sockfd, (struct sockaddr*)&their_addr,   sizeof (struct sockaddr)) == -1) { perror (“connect”); exit (1); }
Sockets API Creation and Setup Establishing a Connection (TCP) Sending and Receiving Data Tearing Down a Connection (TCP)
Sending and Receiving Data Write/Read data to/from a stream (TCP) or “connected” datagram (UDP) socket.  int write (int sockfd, char* buf, size_t nbytes); int read (int sockfd, char* buf, size_t nbytes);  Write/Read a datagram to/from a UDP socket.  int sendto (int sockfd, char* buf, size_t nbytes, int flags,  struct sockaddr* destaddr , int addrlen); int recvfrom (int sockfd, char* buf, size_t nbytes, int flags,  struct sockaddr* srcaddr , int* addrlen);
Functions: 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)
Functions: 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. Returns 0 if socket closed. sockfd : socket file descriptor (returned from  socket ) buf : data buffer nbytes : number of bytes to try to read
Tearing Down a Connection int close (int sockfd); Close a socket.  Returns 0 on success, -1 and sets  errno   on failure. 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.
Functions: close int close (int sockfd); Close a socket.  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.
Functions: 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
UDP Connection Example client server socket socket sendto bind recvfrom sendto recvfrom close
Functions: sendto int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* destaddr, int addrlen); Send a datagram to another UDP socket.  Returns number of bytes written or -1. Also sets  errno   on failure. sockfd : socket file descriptor (returned from  socke t) buf : data buffer nbytes : number of bytes to try to read flags : see man page for details; typically use 0 destaddr : IP address and port number of destination socket addrlen : length of address structure  = sizeof (struct sockaddr_in)
Functions: recvfrom int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* srcaddr, int* addrlen); Read a datagram from a UDP socket.  Returns number of bytes read (0 is valid) 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 flags : see man page for details; typically use 0 srcaddr : IP address and port number of sending socket (returned from call) addrlen : length of address structure = pointer to  int  set to  sizeof (struct sockaddr_in)

More Related Content

What's hot (20)

Multicast Routing Protocols
Multicast Routing ProtocolsMulticast Routing Protocols
Multicast Routing Protocols
Ram Dutt Shukla
 
Route Redistribution
Route RedistributionRoute Redistribution
Route Redistribution
Netwax Lab
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
 
HDLC and Point to point protocol
HDLC and Point to point protocolHDLC and Point to point protocol
HDLC and Point to point protocol
Kinza Razzaq
 
Open shortest path first (ospf)
Open shortest path first (ospf)Open shortest path first (ospf)
Open shortest path first (ospf)
Respa Peter
 
Internetworking
InternetworkingInternetworking
Internetworking
Raghu nath
 
Unicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting NewUnicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting New
techbed
 
Tcp
TcpTcp
Tcp
Varsha Kumar
 
Routing protocols
Routing protocolsRouting protocols
Routing protocols
Sourabh Goyal
 
Common air protocol
Common air protocolCommon air protocol
Common air protocol
Asim khan
 
Dhcp
DhcpDhcp
Dhcp
Chinmoy Jena
 
Imap(internet massege access protocaols)
Imap(internet massege access protocaols)Imap(internet massege access protocaols)
Imap(internet massege access protocaols)
shashikant pabari
 
Tcp
TcpTcp
Tcp
giaolvq
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
tmavroidis
 
Chapter 2 - Computer Networking a top-down Approach 7th
Chapter 2 - Computer Networking a top-down Approach 7thChapter 2 - Computer Networking a top-down Approach 7th
Chapter 2 - Computer Networking a top-down Approach 7th
Andy Juan Sarango Veliz
 
Application Layer
Application Layer Application Layer
Application Layer
Dr Shashikant Athawale
 
Sockets
SocketsSockets
Sockets
Indrasena Reddy
 
Access Control List & its Types
Access Control List & its TypesAccess Control List & its Types
Access Control List & its Types
Netwax Lab
 
Tcp IP Model
Tcp IP ModelTcp IP Model
Tcp IP Model
Ankur Kumar
 
TCP/IP
TCP/IPTCP/IP
TCP/IP
Syed Zaid Irshad
 
Multicast Routing Protocols
Multicast Routing ProtocolsMulticast Routing Protocols
Multicast Routing Protocols
Ram Dutt Shukla
 
Route Redistribution
Route RedistributionRoute Redistribution
Route Redistribution
Netwax Lab
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
CEC Landran
 
HDLC and Point to point protocol
HDLC and Point to point protocolHDLC and Point to point protocol
HDLC and Point to point protocol
Kinza Razzaq
 
Open shortest path first (ospf)
Open shortest path first (ospf)Open shortest path first (ospf)
Open shortest path first (ospf)
Respa Peter
 
Internetworking
InternetworkingInternetworking
Internetworking
Raghu nath
 
Unicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting NewUnicasting , Broadcasting And Multicasting New
Unicasting , Broadcasting And Multicasting New
techbed
 
Common air protocol
Common air protocolCommon air protocol
Common air protocol
Asim khan
 
Imap(internet massege access protocaols)
Imap(internet massege access protocaols)Imap(internet massege access protocaols)
Imap(internet massege access protocaols)
shashikant pabari
 
Tcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport LayerTcp Udp Icmp And The Transport Layer
Tcp Udp Icmp And The Transport Layer
tmavroidis
 
Chapter 2 - Computer Networking a top-down Approach 7th
Chapter 2 - Computer Networking a top-down Approach 7thChapter 2 - Computer Networking a top-down Approach 7th
Chapter 2 - Computer Networking a top-down Approach 7th
Andy Juan Sarango Veliz
 
Access Control List & its Types
Access Control List & its TypesAccess Control List & its Types
Access Control List & its Types
Netwax Lab
 

Viewers also liked (20)

Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
Jignesh Patel
 
Socket programming
Socket programmingSocket programming
Socket programming
harsh_bca06
 
Socket programming
Socket programmingSocket programming
Socket programming
chandramouligunnemeda
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
Avinash Varma Kalidindi
 
Ports & sockets
Ports  & sockets Ports  & sockets
Ports & sockets
myrajendra
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
Amandeep Kaur
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
Tushar B Kute
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
Mousmi Pawar
 
14 M-CARE: Tükenmişlik Sendromunu Önleme
14 M-CARE: Tükenmişlik Sendromunu Önleme14 M-CARE: Tükenmişlik Sendromunu Önleme
14 M-CARE: Tükenmişlik Sendromunu Önleme
Karel Van Isacker
 
Elementary TCP Sockets
Elementary TCP SocketsElementary TCP Sockets
Elementary TCP Sockets
Saksham Khurana
 
Kernel Recipes 2015: Kernel packet capture technologies
Kernel Recipes 2015: Kernel packet capture technologiesKernel Recipes 2015: Kernel packet capture technologies
Kernel Recipes 2015: Kernel packet capture technologies
Anne Nicolas
 
Np unit2
Np unit2Np unit2
Np unit2
vamsitricks
 
Unity Photon server 基礎設施
Unity Photon server 基礎設施Unity Photon server 基礎設施
Unity Photon server 基礎設施
九州 林
 
Sockets
SocketsSockets
Sockets
Thalles Anderson
 
Aula sockets
Aula socketsAula sockets
Aula sockets
Universidade Federal do Pampa
 
Aplicações Web Ricas e Acessíveis
Aplicações Web Ricas e AcessíveisAplicações Web Ricas e Acessíveis
Aplicações Web Ricas e Acessíveis
Synergia - Engenharia de Software e Sistemas
 
Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010
Maurício Linhares
 
Linguagem PHP
Linguagem PHPLinguagem PHP
Linguagem PHP
Bruno Cunha
 

Similar to Basic socket programming (20)

Network Programming Assignment Help
Network Programming Assignment HelpNetwork Programming Assignment Help
Network Programming Assignment Help
HelpWithAssignment.com
 
sockets
socketssockets
sockets
AbhinavRapartiwar
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
SaidiCalala
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
ycelgemici1
 
Sockets
Sockets Sockets
Sockets
Gopaiah Sanaka
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
AnilGupta681764
 
Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
Md. Golam Hossain
 
network programming lab manuaal in this file
network programming lab manuaal in this filenetwork programming lab manuaal in this file
network programming lab manuaal in this file
shivani158351
 
Sockets intro
Sockets introSockets intro
Sockets intro
AviNash ChaVhan
 
Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
elliando dias
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
swtjerin4u
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
AviNash ChaVhan
 
socketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdfsocketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
03-socketprogramming for college students.ppt
03-socketprogramming for college students.ppt03-socketprogramming for college students.ppt
03-socketprogramming for college students.ppt
SoumabhaRoy
 
03-socketprogrsamming forcoleeger students.ppt
03-socketprogrsamming forcoleeger students.ppt03-socketprogrsamming forcoleeger students.ppt
03-socketprogrsamming forcoleeger students.ppt
SoumabhaRoy
 
netLec5.pdf
netLec5.pdfnetLec5.pdf
netLec5.pdf
MuthuramanElangovan
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
elliando dias
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
RockyBhai46825
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
network programming lab manuaal in this file
network programming lab manuaal in this filenetwork programming lab manuaal in this file
network programming lab manuaal in this file
shivani158351
 
Introduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.pptIntroduction to sockets tcp ip protocol.ppt
Introduction to sockets tcp ip protocol.ppt
MajedAboubennah
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
elliando dias
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
swtjerin4u
 
socketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdfsocketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
03-socketprogramming for college students.ppt
03-socketprogramming for college students.ppt03-socketprogramming for college students.ppt
03-socketprogramming for college students.ppt
SoumabhaRoy
 
03-socketprogrsamming forcoleeger students.ppt
03-socketprogrsamming forcoleeger students.ppt03-socketprogrsamming forcoleeger students.ppt
03-socketprogrsamming forcoleeger students.ppt
SoumabhaRoy
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
RockyBhai46825
 

Recently uploaded (20)

CloudStack + KVM: Your Local Cloud Lab
CloudStack + KVM:   Your Local Cloud LabCloudStack + KVM:   Your Local Cloud Lab
CloudStack + KVM: Your Local Cloud Lab
ShapeBlue
 
Interactive SQL: SQL, Features of SQL, DDL & DML
Interactive SQL: SQL, Features of SQL,  DDL & DMLInteractive SQL: SQL, Features of SQL,  DDL & DML
Interactive SQL: SQL, Features of SQL, DDL & DML
IsakkiDeviP
 
Build your own NES Emulator... with Kotlin
Build your own NES Emulator... with KotlinBuild your own NES Emulator... with Kotlin
Build your own NES Emulator... with Kotlin
Artur Skowroński
 
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
UXPA Boston
 
STKI Annual Israel IT Market Study 2025 .
STKI Annual Israel IT Market Study 2025 .STKI Annual Israel IT Market Study 2025 .
STKI Annual Israel IT Market Study 2025 .
Dr. Jimmy Schwarzkopf
 
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PCWondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Mudasir
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Building Agents with LangGraph & Gemini
Building Agents with LangGraph &  GeminiBuilding Agents with LangGraph &  Gemini
Building Agents with LangGraph & Gemini
HusseinMalikMammadli
 
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World TipsMuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
Patryk Bandurski
 
Four Principles for Physically Interpretable World Models
Four Principles for Physically Interpretable World ModelsFour Principles for Physically Interpretable World Models
Four Principles for Physically Interpretable World Models
Ivan Ruchkin
 
Stretching CloudStack over multiple datacenters
Stretching CloudStack over multiple datacentersStretching CloudStack over multiple datacenters
Stretching CloudStack over multiple datacenters
ShapeBlue
 
Dr Schwarzkopf presentation on STKI Summit A
Dr Schwarzkopf presentation on STKI Summit ADr Schwarzkopf presentation on STKI Summit A
Dr Schwarzkopf presentation on STKI Summit A
Dr. Jimmy Schwarzkopf
 
PSEP - Salesforce Power of the Platform.pdf
PSEP - Salesforce Power of the Platform.pdfPSEP - Salesforce Power of the Platform.pdf
PSEP - Salesforce Power of the Platform.pdf
ssuser3d62c6
 
Pushing the Limits: CloudStack at 25K Hosts
Pushing the Limits: CloudStack at 25K HostsPushing the Limits: CloudStack at 25K Hosts
Pushing the Limits: CloudStack at 25K Hosts
ShapeBlue
 
Breaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP DevelopersBreaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP Developers
pmeth1
 
AI Unboxed - How to Approach AI for Maximum Return
AI Unboxed - How to Approach AI for Maximum ReturnAI Unboxed - How to Approach AI for Maximum Return
AI Unboxed - How to Approach AI for Maximum Return
Merelda
 
TAFs on WebDriver API - By - Pallavi Sharma.pdf
TAFs on WebDriver API - By - Pallavi Sharma.pdfTAFs on WebDriver API - By - Pallavi Sharma.pdf
TAFs on WebDriver API - By - Pallavi Sharma.pdf
Pallavi Sharma
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 
How to Integrate FME with Databricks (and Why You’ll Want To)
How to Integrate FME with Databricks (and Why You’ll Want To)How to Integrate FME with Databricks (and Why You’ll Want To)
How to Integrate FME with Databricks (and Why You’ll Want To)
Safe Software
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 
CloudStack + KVM: Your Local Cloud Lab
CloudStack + KVM:   Your Local Cloud LabCloudStack + KVM:   Your Local Cloud Lab
CloudStack + KVM: Your Local Cloud Lab
ShapeBlue
 
Interactive SQL: SQL, Features of SQL, DDL & DML
Interactive SQL: SQL, Features of SQL,  DDL & DMLInteractive SQL: SQL, Features of SQL,  DDL & DML
Interactive SQL: SQL, Features of SQL, DDL & DML
IsakkiDeviP
 
Build your own NES Emulator... with Kotlin
Build your own NES Emulator... with KotlinBuild your own NES Emulator... with Kotlin
Build your own NES Emulator... with Kotlin
Artur Skowroński
 
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
Eating Our Own Dog Food: How to be taken seriously when it comes to adding va...
UXPA Boston
 
STKI Annual Israel IT Market Study 2025 .
STKI Annual Israel IT Market Study 2025 .STKI Annual Israel IT Market Study 2025 .
STKI Annual Israel IT Market Study 2025 .
Dr. Jimmy Schwarzkopf
 
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PCWondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Wondershare Filmora 14.3.2 Crack + License Key Free for Windows PC
Mudasir
 
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
Multi-Agent AI Systems: Architectures & Communication (MCP and A2A)
HusseinMalikMammadli
 
Building Agents with LangGraph & Gemini
Building Agents with LangGraph &  GeminiBuilding Agents with LangGraph &  Gemini
Building Agents with LangGraph & Gemini
HusseinMalikMammadli
 
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World TipsMuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
MuleSoft RTF & Flex Gateway on AKS – Setup, Insights & Real-World Tips
Patryk Bandurski
 
Four Principles for Physically Interpretable World Models
Four Principles for Physically Interpretable World ModelsFour Principles for Physically Interpretable World Models
Four Principles for Physically Interpretable World Models
Ivan Ruchkin
 
Stretching CloudStack over multiple datacenters
Stretching CloudStack over multiple datacentersStretching CloudStack over multiple datacenters
Stretching CloudStack over multiple datacenters
ShapeBlue
 
Dr Schwarzkopf presentation on STKI Summit A
Dr Schwarzkopf presentation on STKI Summit ADr Schwarzkopf presentation on STKI Summit A
Dr Schwarzkopf presentation on STKI Summit A
Dr. Jimmy Schwarzkopf
 
PSEP - Salesforce Power of the Platform.pdf
PSEP - Salesforce Power of the Platform.pdfPSEP - Salesforce Power of the Platform.pdf
PSEP - Salesforce Power of the Platform.pdf
ssuser3d62c6
 
Pushing the Limits: CloudStack at 25K Hosts
Pushing the Limits: CloudStack at 25K HostsPushing the Limits: CloudStack at 25K Hosts
Pushing the Limits: CloudStack at 25K Hosts
ShapeBlue
 
Breaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP DevelopersBreaking it Down: Microservices Architecture for PHP Developers
Breaking it Down: Microservices Architecture for PHP Developers
pmeth1
 
AI Unboxed - How to Approach AI for Maximum Return
AI Unboxed - How to Approach AI for Maximum ReturnAI Unboxed - How to Approach AI for Maximum Return
AI Unboxed - How to Approach AI for Maximum Return
Merelda
 
TAFs on WebDriver API - By - Pallavi Sharma.pdf
TAFs on WebDriver API - By - Pallavi Sharma.pdfTAFs on WebDriver API - By - Pallavi Sharma.pdf
TAFs on WebDriver API - By - Pallavi Sharma.pdf
Pallavi Sharma
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 
How to Integrate FME with Databricks (and Why You’ll Want To)
How to Integrate FME with Databricks (and Why You’ll Want To)How to Integrate FME with Databricks (and Why You’ll Want To)
How to Integrate FME with Databricks (and Why You’ll Want To)
Safe Software
 
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCPMCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
MCP Dev Summit - Pragmatic Scaling of Enterprise GenAI with MCP
Sambhav Kothari
 

Basic socket programming

  • 1. Network Programming with Sockets Reading: Stevens 3rd ed., Ch. 3-6, or 2 nd ed. Beej's Guide to Network Programming http://beej.us/guide/bgnet/
  • 2. Outline Basic socket programming Concurrent communication Libnet and libcap library
  • 3. Sockets process sends/receives messages to/from its socket socket analogous to door sending process shoves message out door sending process relies on transport infrastructure on other side of door which brings message to socket at receiving process Internet controlled by app developer process TCP with buffers, variables socket host or server process TCP with buffers, variables socket host or server
  • 4. Client-Server Model Asymmetric Communication Client sends requests Server sends replies Server/Daemon Well-known name (e.g., IP address + port) Waits for contact Processes requests, sends replies Client Initiates contact Waits for response Client Server Client Client Client
  • 5. Client-Server Communication Model Service Model Concurrent: Server processes multiple clients’ requests simultaneously Sequential: Server processes only one client’s requests at a time Hybrid: Server maintains multiple connections, but processes responses sequentially Client and server categories are not disjoint A server can be a client of another server A server can be a client at the same time Example?
  • 6. TCP Service Reliable Data Transfer Guarantees delivery of all data Exactly once if no catastrophic failures Ordered Data Transfer Guarantees in-order delivery of data If A sends M1 followed by M2 to B, B never receives M2 before M1 Regulated Data Flow Monitors network and adjusts transmission appropriately Prevents senders from wasting bandwidth Reduces global congestion problems Data Transmission Full-Duplex byte stream Connection setup and teardown
  • 7. UDP Services User Datagram Protocol Service Provides a thin layer over IP 16-bit port space (distinct from TCP ports) allows multiple recipients on a single host
  • 8. UDP Services Unit of Transfer Datagram (variable length packet) Unreliable No guaranteed delivery Drops packets silently Unordered No guarantee of maintained order of delivery Unlimited Transmission No flow control
  • 9. Byte Ordering Big Endian vs. Little Endian Little Endian (Intel, DEC): Least significant byte of word is stored in the lowest memory address Big Endian (Sun, SGI, HP): Most significant byte of word is stored in the lowest memory address Network Byte Order = Big Endian Allows both sides to communicate Must be used for some data (i.e. IP Addresses) Good form for all binary data Most significant Byte 0xAA Least significant Byte 0xBB Least significant Byte 0xBB Most significant Byte 0xAA 0x1000 0x1001 Big-Endian (Network-Byte-Order) Little-Endian Memory address
  • 10. Byte Ordering Functions 16- and 32-bit conversion functions (for platform independence) Examples: int m, n; short int s,t; m = ntohl (n) net-to-host long (32-bit) translation s = ntohs (t) net-to-host short (16-bit) translation n = htonl (m) host-to-net long (32-bit) translation t = htons (s) host-to-net short (16-bit) translation
  • 11. BSD Sockets BSD Sockets PF_INET sockets PF_PACKET Socket PF_NETLINK Socket TCP UDP IP Network device SOCK_ STREAM SOCK_ DGRAM SOCK_ RAW
  • 12. BSD Socket Structure include/linux/net.h struct socket { socket_state state;/* SS_CONNECTED .. */ unsigned long flags; struct proto_ops *ops;/*protocols do most everything*/ struct fasync_struct *fasync_list; struct file *file; struct sock *sk; /*hold protocol specific info*/ wait_queue_head_t wait; short type;/*SOCKET_STREAM */ unsigned char passcred; }; struct sock { … struct sk_buff_head sk_receive_queue; struct sk_buff_head sk_write_queue; }
  • 13. struct proto_ops { int family; struct module *owner; int (*release) (struct socket *sock); int (*bind) (struct socket *sock, struct sockaddr *myaddr, int sockaddr_len); int (*connect) (struct socket *sock, struct sockaddr *vaddr, int sockaddr_len, int flags); int (*socketpair)(struct socket *sock1, struct socket *sock2); int (*accept) (struct socket *sock, struct socket *newsock, int flags); int (*getname) (struct socket *sock, struct sockaddr *addr, int *sockaddr_len, int peer); unsigned int (*poll) (struct file *file, struct socket *sock, struct poll_table_struct *wait); int (*ioctl) (struct socket *sock, unsigned int cmd, unsigned long arg); int (*listen) (struct socket *sock, int len); int (*shutdown) (struct socket *sock, int flags); int (*setsockopt)(struct socket *sock, int level, int optname, char __user *optval, int optlen); int (*getsockopt)(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen); int (*sendmsg) (struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len); int (*recvmsg) (struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags); … };
  • 14. Socket Address Structure Socket address struct sockaddr { short sa_family; char sa_data[14]; }; Internet address: struct sockaddr_in { short sin_family; /* e.g., AF_INET */ ushort sin_port; /* TCP/UDP port */ struct in_addr sin_addr; /* IP address */ unsigned char sin_zero[8]; /* Same size as struct sockaddr */ }; IP address: struct in_addr { in_addr_t s_addr; /* 32-bit IP address */ }; all but sin_family in network byte order
  • 15. Address Access/Conversion Functions All binary values are network byte ordered struct hostent* gethostbyname (const char* hostname); Translate English host name to IP address (uses DNS) struct hostent* gethostbyaddr (const char* addr, size_t len, int family); Translate IP address to English host name (not secure) Better used in combination of gethostbyname() to validate the results char* inet_ntoa (struct in_addr inaddr); Translate IP address to ASCII dotted-decimal notation (e.g., “128.32.36.37”) int gethostname (char* name, size_t namelen); Read host’s name (use with gethostbyname to find local IP) (/etc/hosts)
  • 16. Structure: hostent The hostent data structure (from /usr/include/netdb. h ) canonical domain name and aliases list of addresses associated with machine also address type and length information struct hostent { char* h_name; /* official name of host */ char** h_aliases; /* NULL-terminated alias list */ int h_addrtype /* address type (AF_INET) */ int h_length; /* length of addresses (4B) */ char** h_addr_list; /* NULL-terminated address list */ #define h_addr h_addr_list[0];/* backward-compatibility */ };
  • 17. Address Access/Conversion Functions in_addr_t inet_addr (const char* strptr); Translate dotted-decimal notation to IP address (Network Byte Order); returns -1 on failure, thus cannot handle broadcast value “255.255.255.255” struct sockaddr_in ina; ina.sin_addr.s_addr = inet_addr(&quot;10.12.110.57&quot;); int inet_aton (const char *strptr, struct in_addr *inaddr); Translate dotted-decimal notation to IP address; returns 1 on success, 0 on failure struct sockaddr_in my_addr; my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order inet_aton(&quot;10.12.110.57&quot;,&(my_addr.sin_addr)); memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct
  • 18. Sockets API Creation and Setup Establishing a Connection (TCP) Sending and Receiving Data Tearing Down a Connection (TCP)
  • 19. Socket Functions blocks until connection from client TCP Client TCP Server socket() listen() accept() socket() bind() Well-known port connect() write() TCP three-way handshaking data (request) read() process request
  • 20. Socket Functions blocks until connection from client TCP Server TCP Client read() data (reply) close() read() close() socket() connect() write() TCP three-way handshaking data (request) read() process request write()
  • 21. Socket Creation and Setup Include file <sys/socket.h> Create a socket int socket (int domain, int type, int protocol); Returns file descriptor or -1. Bind a socket to a local IP address and port number int bind (int sockfd, struct sockaddr* myaddr, int addrlen); Put socket into passive state (wait for connections rather than initiate a connection). int listen (int sockfd, int backlog); Accept connections int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Returns file descriptor or -1.
  • 22. Functions: socket int socket (int domain, int type, int protocol); Create a socket. Returns file descriptor or -1. Also sets errno on failure. domain : protocol family (same as address family) PF_INET for IPv4 other possibilities: PF_INET6 (IPv6), PF_UNIX or PF_LOCAL (Unix socket), PF_ROUTE (routing) type : style of communication SOCK_STREAM for TCP (with PF_INET ) SOCK_DGRAM for UDP (with PF_INET ) protocol : protocol within family typically 0 getprotobyname(), /etc/protocols for list of protocols
  • 23. Function: 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 addrlen : length of address structure = sizeof (struct sockaddr_in) socket.socket_state = TCP_CLOSE;
  • 24. TCP and UDP Ports Allocated and assigned by the Internet Assigned Numbers Authority see RFC 1700 or ftp://ftp.isi.edu/in-notes/iana/assignments/port-numbers private/ephemeral ports 49152-65535 registered services/ephemeral ports 1024-49151 registered and controlled, also used for identity verification super-user only 513-1023 standard services (see /etc/services ) super-user only 1-512
  • 25. Functions: 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 socket.socket_state = TCP_LISTEN;
  • 26. Functions: accept int accept (int sockfd, struct sockaddr* cliaddr, int* addrlen); Accept a new connection. Returns file descriptor or -1. Also sets errno on failure. 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 the client’s address (the number of bytes written)
  • 27. Accept (cont'd) A new socket was cloned from the listening socket If there are no incoming connection to accept Non-Blocking—accept operation failed and throw away the new socket Blocking—accept operation was added to the wait queue (default)
  • 28. TCP Connection Setup client server socket socket connect bind listen accept connect completes connection added to incomplete queue connection moved to complete queue Synchronize (SYN) J SYN K, acknowledge (ACK) J+1 ACK K+1
  • 29. server #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/wait.h> #define PORT 3490 #define BACKLOG 10 /* how many pending connections queue will hold */
  • 30. server main() { int sockfd, new_fd; /* listen on sock_fd, new connection on new_fd */ struct sockaddr_in my_addr; /* my address */ struct sockaddr_in their_addr; /* connector addr */ int sin_size; if ((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){ perror(&quot;socket&quot;); exit(1); }
  • 31. server my_addr.sin_family = AF_INET; /* host byte order */ my_addr.sin_port = htons(MYPORT); /* short, network byte order */ my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* INADDR_ANY allows clients to connect to any one of the host’s IP address */ bzero(&(my_addr.sin_zero), 8); /* zero the struct */ if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror(&quot;bind&quot;); exit(1); }
  • 32. server if (listen(sockfd, BACKLOG) == -1) { perror(&quot;listen&quot;); exit(1); } while(1) { /* main accept() loop */ sin_size = sizeof(struct sockaddr_in); if ((new_fd = accept(sockfd, (struct sockaddr*) &their_addr,&sin_size)) == -1) { perror(&quot;accept&quot;); continue; } printf(&quot;server: got connection from %s\n&quot;, inet_ntoa(their_addr.sin_addr));
  • 33. Establishing a Connection Include file <sys/socket.h> 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)
  • 34. Connect Before connecting, socket.socket_state = SS_UNCONNECTED; Add the sock to tcp_listening_hash waiting for server’s response
  • 35. client if ((sockfd = socket (PF_INET, SOCK_STREAM, 0)) == -1) { perror (“socket”); exit (1); } their_addr.sin_family = AF_INET; /* interp’d by host */ their_addr.sin_port = htons (PORT); their_addr.sin_addr = *((struct in_addr*)he->h_addr); bzero (&(their_addr.sin_zero), 8); /* zero rest of struct */ if (connect (sockfd, (struct sockaddr*)&their_addr, sizeof (struct sockaddr)) == -1) { perror (“connect”); exit (1); }
  • 36. Sockets API Creation and Setup Establishing a Connection (TCP) Sending and Receiving Data Tearing Down a Connection (TCP)
  • 37. Sending and Receiving Data Write/Read data to/from a stream (TCP) or “connected” datagram (UDP) socket. int write (int sockfd, char* buf, size_t nbytes); int read (int sockfd, char* buf, size_t nbytes); Write/Read a datagram to/from a UDP socket. int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* destaddr , int addrlen); int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* srcaddr , int* addrlen);
  • 38. Functions: 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)
  • 39. Functions: 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. Returns 0 if socket closed. sockfd : socket file descriptor (returned from socket ) buf : data buffer nbytes : number of bytes to try to read
  • 40. Tearing Down a Connection int close (int sockfd); Close a socket. Returns 0 on success, -1 and sets errno on failure. 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.
  • 41. Functions: close int close (int sockfd); Close a socket. 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.
  • 42. Functions: 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
  • 43. UDP Connection Example client server socket socket sendto bind recvfrom sendto recvfrom close
  • 44. Functions: sendto int sendto (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* destaddr, int addrlen); Send a datagram to another UDP socket. Returns number of bytes written or -1. Also sets errno on failure. sockfd : socket file descriptor (returned from socke t) buf : data buffer nbytes : number of bytes to try to read flags : see man page for details; typically use 0 destaddr : IP address and port number of destination socket addrlen : length of address structure = sizeof (struct sockaddr_in)
  • 45. Functions: recvfrom int recvfrom (int sockfd, char* buf, size_t nbytes, int flags, struct sockaddr* srcaddr, int* addrlen); Read a datagram from a UDP socket. Returns number of bytes read (0 is valid) 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 flags : see man page for details; typically use 0 srcaddr : IP address and port number of sending socket (returned from call) addrlen : length of address structure = pointer to int set to sizeof (struct sockaddr_in)
  翻译: