Overview Client erver pocket socket en listened open clientfd listen Connection connec七 reguest accept Client wri七e read Server Session read wri七e c1。se EOF ad close
Client / Server Session Client Server socket socket bind listen read read write write Connection request read close close EOF open_listenfd connect accept open_clientfd Overview
Step 1- Setup Socket Both client and server need to setup the socket int socket(int domain, int type, int protocol), domain AF INET--IPv4(AF INET6 for IPv6 °type SOCK STREAM-- TCP SOCK DGRAM--UDP ● protoco For example, int sockfd socket(AF INET, SOCK STREAM, O;
Step 1 – Setup Socket • Both client and server need to setup the socket – int socket(int domain, int type, int protocol); • domain – AF_INET -- IPv4 (AF_INET6 for IPv6) • type – SOCK_STREAM -- TCP – SOCK_DGRAM -- UDP • protocol – 0 • For example, – int sockfd = socket(AF_INET, SOCK_STREAM, 0);
Step 2( Server )-Binding Only server need to bind int bind(int sockfd, const struct sockaddr *my addr, socklen taddrlen sockfd file descriptor socket returned my addr struct sockaddr in for ipv4 cast (struct sockaddr in )to struct sockaddr struct sockaddr in sin family; //e.g. AF_INET unsigned short sin port; //e.g. htons (3490 truct in addr sin addr; / see struct in addr, below sin zero[8];// zero this if you want to } struct in addr unsigned long s addr; // load with inet aton(
Step 2 (Server) - Binding • Only server need to bind – int bind(intsockfd, const structsockaddr *my_addr, socklen_t addrlen); • sockfd – file descriptor socket() returned • my_addr – structsockaddr_in for IPv4 – cast (structsockaddr_in*) to (structsockaddr*) struct sockaddr_in { short sin_family; // e.g. AF_INET unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; struct in_addr { unsigned long s_addr; // load with inet_aton() };