Dept. of Computer Science & Engineering 1 Knowledge & Data Engineering Lab.
|
|
- Noreen Hutchinson
- 5 years ago
- Views:
Transcription
1 Socket Programming Dept. of Computer Science & Engineering 1
2 Socket A socket is a communication end point. Is equivalent to a computer s network (hardware) interface. Allows a network application to plug into the network (not physically, but metaphorically). Is a network programming interface. It is used for interprocess communication over the network. Is used by a process to communicate with a remote system via a transport protocol. Needs an IP address and a port number. Sockets were first introduced in Berkeley UNIX. An extension of the UNIX abstraction of file I/O concepts. Now are commonly supported in almost all modern operating systems for inter-systems communications. Dept. of Computer Science & Engineering 2
3 Socket Computing A socket provides a two-way communication mechanism Provides two major types of services: Connection-oriented (TCP/IP) Stream Reliable Bi-directional communication Connectionless (UDP/IP) Datagram Unreliable Bi-directional communication Dept. of Computer Science & Engineering 3
4 Connection-Oriented Implemented on TCP Short for Transmission Control Protocol. An end-to-end connection is established before data exchange can happen. Similar to our phone system. Data bytes are delivered in sequence. Delivery of data is guaranteed. Connection is terminated when finished. Two modes: Iterative (synchronous) Concurrent (asynchronous) Dept. of Computer Science & Engineering 4
5 Connectionless Implemented on UDP Short for User Datagram Protocol. No connection is required before data transfer. Similar to our postal system. Data bytes may be missing or delivered out-of-order. Two modes: Iterative (synchronous) Concurrent (asynchronous) Dept. of Computer Science & Engineering 5
6 Internet Addressing IP addresses A means to identify hosts on the Internet. IP is short for Internet Protocol. Each host on the Internet is assigned a 32-bit unique address (in IPv4). An IP address is assigned to a single host only. Dotted representation Internet addresses are represented in the form of four integers separated by decimal points. For readability by human An example:» Dept. of Computer Science & Engineering 6
7 DNS The domain name system (DNS) A high-level naming scheme. A sequence of characters grouped into sections delimited by decimal points. Labeled in a meaningful way A hierarchical naming system Mapping of high-level domain names to low level IP addresses is needed for communications across the Internet. Done at system startup via a local table lookup. Going through a name server (DNS server). Dept. of Computer Science & Engineering 7
8 Port Numbers (1) A (protocol) port is an abstraction used by TCP/UDP to distinguish applications on a given host. A port is identified by a 16-bit integer known as the port number. Three ranges of port numbers: Well-known ports Registered ports Dynamic ports Well-known ports Ranging from 0 to 1,023. A set of pre-assigned port numbers for specific uses. Are controlled by IANA (Internet Assigned Numbers Authority). Dept. of Computer Science & Engineering 8
9 Port Numbers (2) Registered ports Ranging from 1,024 to 49,151. Not assigned or controlled by IANA; however their uses need to be registered with IANA to prevent duplications. Dynamic ports Ranging from 49,152 to 65,535. Neither assigned or registered. They can be used by anyone. These are ephemeral ports. Also known as private ports. Dept. of Computer Science & Engineering 9
10 Some Well-Known Ports Dept. of Computer Science & Engineering 10
11 Socket Address Structure (1) To hold address and port number information. A generic format (address family (or domain), address in the family) Generic socket address structure: struct sockaddr { sa_family_t sa_family; /* address family */ char sa_data[14]; /* socket address */ ; A popular BSD-derived implementation: struct sockaddr_in { sa_family_t sin_family; /* address family */ in_port_t sin_port; /* protocol port number */ struct in_addr sin_addr; /* IP addr in NW byte order */ char sin_zero[8]; /* unused, set to zero */ ; Dept. of Computer Science & Engineering 11
12 Socket Address Structure (2) sa_family_t sin_family usually holds the value either AF_INET or AF_UNIX. in_port_t sin_port is a 16-bit TCP or UDP port number. in_addr sin_addr contains a 32-bit IPv4 address. Structure for in_addr: struct in_addr { in_addr_t sa_s_addr; /* 32-bit IPv4 address */ ; Dept. of Computer Science & Engineering 12
13 TCP Server Example An algorithm for server STEP 1: Create a socket. STEP 2: Bind to a predefined address for the service desired. STEP 3: Start listening for incoming connections. STEP 4: Accept the next connection request from a client. STEP 5: Read a request, process the request (fork or thread), and send back the results. STEP 6: Close the connection when done with a client. STEP 7: Return to STEP 3 for next client. (After forking in STEP 5, the parent process immediately returns to STEP 4.) Dept. of Computer Science & Engineering 13
14 TCP Client Example An algorithm for client STEP 1: Create a socket. STEP 2: Connect the socket to the desired server. STEP 3: Send a request, and wait for the response. STEP 4: Repeat STEP 3 until done. STEP 5: Notify server of intention to terminate. STEP 6: Close the socket (connection). Dept. of Computer Science & Engineering 14
15 TCP System Calls Server socket() bind() listen() accept() blocks until connection from client Client socket() connect() read() process request write() write() read() close() close() Dept. of Computer Science & Engineering 15
16 UDP Server/Client Example An algorithm for server STEP 1: Create a socket. STEP 2: Bind to a predefined address for the service desired. STEP 3: Wait for a datagram to arrive from a client. STEP 4: Send response back to originating client. STEP 5: Return to STEP 3 for next client. An algorithm for client STEP 1: Create a socket. STEP 2: Send a datagram to server. STEP 3: Wait for response from server. STEP 4: Return to STEP 2 for more datagrams. STEP 5: Close the socket. Dept. of Computer Science & Engineering 16
17 UDP System Calls Server socket() bind() recvfrom() blocks until data received from a client process request data(request) Client socket() sendto() sendto() data(reply) recvfrom() close() Dept. of Computer Science & Engineering 17
18 Some Socket System Calls #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> int socket(int family, int type, int protocol); int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int listen(int sockfd, int backlog); int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *cliaddrlen); int connect(int sockfd, struct sockaddr *servaddr, socklen_t *servaddrlen); ssize_t recvfrom(int sockfd, void *buff, size_t len, int flags, struct sockaddr *from, socklen_t *fromlen); ssize_t sendto(int sockfd, void *msg, size_t len, int flags, struct sockaddr *to, socklen_t tolen); struct hostent *gethostbyname(const char *name); int shutdown(int sockfd, int howto); Dept. of Computer Science & Engineering 18
19 More on Sockets In a TCP connection, a write to a disconnected socket will generate SIGPIPE signal. This can be dealt with a proper signal handler. A read from socket will return 0, if the socket is closed. With a close( ) call, If the socket is of SOCK_STREAM type, The kernel will deliver all data received before terminating the connection. close( ) will block until all outstanding data delivered to the receiving process. If the socket is of SOCK_DGRAM type, The socket is closed immediately. Dept. of Computer Science & Engineering 19
20 Multiplexing on Sockets The select( ) system call It is used for handling multiple file descriptors simultaneously. It can indicate which of the specified file descriptors is ready for reading, writing, or has an error condition pending. It may block until the condition is true for at least one of the specified file descriptors. It may return immediately or wait up to a certain amount of time, depending on the timeout value specified. The types of file descriptors supported include regular files, terminal and pseudo-terminal devices, FIFOs, pipes, and sockets. Dept. of Computer Science & Engineering 20
21 Socket (1) #include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); domain Specify address family AF_UNIX : UNIX domain AF_INET : IPv4 Internet domain AF_INET6 : IPv6 Internet domain AF_UNSPEC : unspecified type Socket types SOCK_STREAM : sequenced, reliable, connection-oriented byte streams SOCKET_DGRAM : fixed-length, connectionless, unreliable messages SOCKET_SEQPACKET : fixed-length, sequenced, reliable, connection-oriented messages SOCK_RAW : raw socket (talk to IP directly), optional in POSIX.1 Dept. of Computer Science & Engineering 21
22 Socket (2) protocol If 0, system determines (IPPROTO_TCP, IPPROTO_UDP). Return value Socket descriptor; -1 if failure. Dept. of Computer Science & Engineering 22
23 bind #include <sys/types.h> #include <sys/socket.h> int bind(int sockfd, struct sockaddr *my_addr, int addrlen); Assigning a name to a socket. sockfd: obtained from socket( ). struct sockaddr is a generic address structure. addrlen is the length of my_addr object. Need to cast the real data structures. Unix domain: struct sockaddr_un, <sys/un.h> Internet domain: struct sockaddr_in, <netinet/in.h> Dept. of Computer Science & Engineering 23
24 listen #include <sys/socket.h> int listen(int sockfd, int backlog); Create a queue for incoming connection requests. sockfd Socket descriptor backlog Maximum size of the queue Apply only to sockets of type SOCK_STREAM or SOCK_SEQPACKET. Return -1 if failure. Dept. of Computer Science & Engineering 24
25 accept #include <sys/types.h> #include <sys/socket.h> int accept(int sockfd, struct sockaddr *addr, int *addrlen); Accept a connection on a socket. Blocked if there are no pending requests. sockfd: socket descriptor addr, addrlen: client information and length of it Return new socket descriptor that can be used for reading and writing. Used by server processes. Dept. of Computer Science & Engineering 25
26 connect #include <sys/types.h> #include <sys/socket.h> int connect(int sockfd, struct sockaddr *serv_addr, int addrlen); sockfd Socket descriptor obtained from socket( ). serv_addr, addrlen Server address information A stream socket in connected only once, while a datagram socket can be connected several times. Used by client processes. Dept. of Computer Science & Engineering 26
27 Send and Receive (1) send( ), sendto( ), recv( ), recvfrom( ) system call Similar to read, write system calls but needs additional arguments. int send(int sockfd, char *buff, int nbytes, int flags); int sendto(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *to, int addrlen); int recv(int sockfd, char *buff, int nbytes, int flags); int recvfrom(int sockfd, char *buff, int nbytes, int flags, struct sockaddr *from, int *addrlen); Flags Affects the way in which the data can be received or sent If flags is zero, send() and recv() are behaves just like write() and read() flags: MSG_OOB, MSG_PEEK, MSG_WAITALL, MSG_DONTROUTE Dept. of Computer Science & Engineering 27
28 Send and Receive (2) MSG_OOB : Normal data is bypassed and the process only receives out of band data, for example, an interrupt signal MSG_PEEK : let the caller look at the data that available to be read, without having the system discard the data after the recv() or recvfrom() returns MSG_WAITALL : recv() call will only return when the full amount of data is available MSG_DONTROUTE : the message will be sent ignoring any routing conditions of the underlying protocol Return values Length of the data written or read. Dept. of Computer Science & Engineering 28
29 Close/shutdown int close(int sockfd); Used to close a socket. int shutdown (int sockfd, int howto) Used to close a socket, but provide more control over full-duplex connection Howto 0 : close a sock for reading 1 : close a sock for writing 2 : close a sock for reading and writing Dept. of Computer Science & Engineering 29
30 Example #1: UNIX Domain (1) /* Server -- UNIX domain stream socket */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> /* as we are using UNIX protocol */ #define NAME "my_sock" int main(void) { int orig_sock; /* Original socket descriptor in server */ int new_sock; /* New socket descriptor from connect */ int clnt_len; /* Length of client address */ int i; /* Loop counter */ Dept. of Computer Science & Engineering 30
31 Example #1: UNIX Domain (2) static struct sockaddr_un clnt_adr; /* UNIX addresses of client */ static struct sockaddr_un serv_adr; /* UNIX addresses of server */ static char buf[10]; /* Buffer for messages */ void clean_up(int, char *); /* Close socket and remove it routine */ if ((orig_sock = socket(af_unix, SOCK_STREAM, 0)) < 0) { /* SOCKET */ perror("generate error"); exit(1); serv_adr.sun_family = AF_UNIX; /* Set tag appropriately */ strcpy(serv_adr.sun_path, NAME); /* Assign name (108 chars max) */ unlink(name); /* Remove old copy if present */ if (bind(orig_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr.sun_family)+strlen(serv_adr.sun_path)) < 0) { perror("bind error"); clean_up(orig_sock, NAME); exit(2); Dept. of Computer Science & Engineering 31
32 Example #1: UNIX Domain (3) listen(orig_sock, 1); /* LISTEN; create one-entry queue */ clnt_len = sizeof(clnt_adr); /* clnt_len = 110 */ if ((new_sock = accept(orig_sock, (struct sockaddr *)&clnt_adr, &clnt_len)) < 0) { perror("accept error"); clean_up(orig_sock, NAME); exit(3); for (i = 1; i <= 10; i++) { /* Process */ read(new_sock, buf, sizeof(buf)); printf("s-> %s", buf); close(new_sock); clean_up(orig_sock, NAME); exit(0); Dept. of Computer Science & Engineering 32
33 Example #1: UNIX Domain (4) void clean_up(int sd, char *the_file) { close(sd); /* close it */ unlink(the_file); /* remove it */ Dept. of Computer Science & Engineering 33
34 Example #1: UNIX Domain (5) /* Client -- UNIX domain stream socket */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define NAME "my_sock int main(void) { int orig_sock; /* Original socket descriptor in client */ int i; /* Loop counter */ static struct sockaddr_un serv_adr; /* UNIX address of the server process */ static char buf[10]; /* Buffer for messages */ Dept. of Computer Science & Engineering 34
35 Example #1: UNIX Domain (6) if ((orig_sock = socket(af_unix, SOCK_STREAM, 0)) < 0) { /* SOCKET */ perror("generate error"); exit(1); serv_adr.sun_family = AF_UNIX; /* Set tag appropriately */ strcpy(serv_adr.sun_path, NAME);/* Assign name */ if (connect(orig_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr.sun_family)+strlen(serv_adr.sun_path)) < 0) { perror("connect error"); exit(1); for (i = 1; i <= 10; i++) { /* Send msgs */ sprintf(buf, "c: %d\n", i); write(orig_sock, buf, sizeof(buf)); close(orig_sock); exit(0); Dept. of Computer Science & Engineering 35
36 Sample Run Dept. of Computer Science & Engineering 36
37 Host Name Conversion #include <netdb.h> extern int h_errno; struct hostent *gethostbyname(const char *name); name: hostname, IPv4 or IPv6 address #include <sys/socket.h> /* for AF_INET */ struct hostent *gethostbyaddr(const char *addr, int len, int type); addr, len: IP address type: AF_INET is the only valid type. void herror(const char *s); Print error message Dept. of Computer Science & Engineering 37
38 Host Entry Structure (1) The hostent structure is defined in <netdb.h> as follows: struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ #define h_addr h_addr_list[0] /* first address in list */ Dept. of Computer Science & Engineering 38
39 Host Entry Structure (2) The members of the hostent structure are: h_name The official name of the host. h_aliases A zero-terminated array of alternative names for the host. h_addrtype The type of address; always AF_INET at present. h_length The length of the address in bytes. h_addr_list A zero-terminated array of network addresses for the host in network byte order. h_addr The first address in h_addr_list Dept. of Computer Science & Engineering 39
40 Byte Ordering Conversion (1) htonl, htons, ntohl, ntohs Handle the potential byte order differences between different computer architectures and different network protocols So, convert values between host and network byte order On the i80x86, the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first For example, Ox4F52 Dept. of Computer Science & Engineering 40
41 Byte Ordering Conversion (2) #include <netinet/in.h> unsigned long int htonl(unsigned long int hostlong); Converts the long integer hostlong from host byte order to network byte order. unsigned short int htons(unsigned short int hostshort); unsigned long int ntohl(unsigned long int netlong); unsigned short int ntohs(unsigned short int netshort); Dept. of Computer Science & Engineering 41
42 Address Manipulation (1) inet_aton, inet_addr, inet_network, inet_ntoa : Internet address manipulation routines. #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int inet_aton(const char *cp, struct in_addr *inp); inet_aton converts the Internet host address cp from the standard numbers-and-dots notation into binary data and stores it in the structure that inp points to. inet_aton returns nonzero if the address is valid, zero if not. Dept. of Computer Science & Engineering 42
43 Address Manipulation (2) unsigned long int inet_addr(const char *cp); Converts the Internet host address cp from numbers-and-dots notation into binary data in network byte order. unsigned long int inet_network(const char *cp); Extracts the network number in host byte order from the address cp in numbers-and-dots notation. char *inet_ntoa(struct in_addr in); Converts the Internet host address in given in network byte order to a string in standard numbers-and-dots notation (note: it returns a pointer to a static buffer!). Dept. of Computer Science & Engineering 43
44 Example #2: Internet Domain (1) /* local.h -- header file */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/ioctl.h> #define PORT 6969 static char buf[bufsiz]; /* Buffer for messages */ Dept. of Computer Science & Engineering 44
45 Example #2: Internet Domain (2) /* Server -- Internet domain stream socket */ #include "local.h" int main(void) { int orig_sock; /* Original socket descriptor in server */ int new_sock; /* New socket descriptor from connect */ int clnt_len; /* Length of client address */ static struct sockaddr_in clnt_adr; /* Internet address of client */ static struct sockaddr_in serv_adr; /* Internet address of server */ static char buf[bufsiz]; /* Buffer for messages */ int len, i; /* Misc counters, etc. */ if ((orig_sock = socket(af_inet, SOCK_STREAM, 0)) < 0) { /* SOCKET */ perror("generate error"); exit(1); Dept. of Computer Science & Engineering 45
46 Example #2: Internet Domain (3) memset(&serv_adr, 0, sizeof(serv_adr)); /* Clear it out */ serv_adr.sin_family = AF_INET; /* Set address type */ serv_adr.sin_addr.s_addr = htonl(inaddr_any); /* Any interface */ serv_adr.sin_port = htons(port); /* Use our fake port */ /* BIND */ if (bind(orig_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) < 0) { perror("bind error"); close(orig_sock); exit(2); /* LISTEN */ if (listen(orig_sock, 5) < 0 ) { perror("listen error"); exit(3); Dept. of Computer Science & Engineering 46
47 Example #2: Internet Domain (4) do { /* ACCEPT */ clnt_len = sizeof(clnt_adr); if ((new_sock = accept(orig_sock, (struct sockaddr *)&clnt_adr, &clnt_len)) < 0) { perror("accept error"); close(orig_sock); exit(4); if (fork() == 0) { /* In CHILD process */ while ((len = read(new_sock, buf, BUFSIZ)) > 0) { for (i = 0; i < len; ++i) /* Change the case */ buf[i] = toupper(buf[i]); write(new_sock, buf, len); /* write it back */ if (buf[0] == '.') break; /* are we done yet? */ close(new_sock); /* In CHILD process */ exit(0); else close(new_sock); /* In PARENT process */ while(1); /* FOREVER */ /* main */ Dept. of Computer Science & Engineering 47
48 Example #2: Internet Domain (5) /* Client -- Internet domain stream socket */ #include "local.h" int main(int argc, char *argv[]) { int orig_sock, len; static struct sockaddr_in serv_adr; struct hostent *host; if (argc!= 2) { fprintf(stderr, "usage: %s server\n", argv[0]); exit(1); host = gethostbyname(argv[1]); /* GET INFO */ if (host == (struct hostent *)NULL) { perror("gethostbyname "); exit(2); Dept. of Computer Science & Engineering 48
49 Example #2: Internet Domain (6) memset(&serv_adr, 0, sizeof(serv_adr)); /* Clear it out */ serv_adr.sin_family = AF_INET; memcpy(&serv_adr.sin_addr, host->h_addr, host->h_length); serv_adr.sin_port = htons(port); /* SOCKET */ if ((orig_sock = socket(af_inet, SOCK_STREAM, 0)) < 0) { perror("generate error"); exit(3); /* CONNECT */ if (connect(orig_sock, (struct sockaddr *)&serv_adr, sizeof(serv_adr)) < 0) { perror("connect error"); exit(4); Dept. of Computer Science & Engineering 49
50 Example #2: Internet Domain (7) do { write(fileno(stdout),"> ", 3); /* Prompt the user */ if ((len = read(fileno(stdin), buf, BUFSIZ)) > 0) { /* Get user input */ write(orig_sock, buf, len); /* Write to socket */ if ((len = read(orig_sock, buf, len)) > 0 ) /* If returned */ write(fileno(stdout), buf, len); /* display it. */ while(buf[0]!= '.'); close(orig_sock); exit(0); /* main */ Dept. of Computer Science & Engineering 50
51 Sample Run Dept. of Computer Science & Engineering 51
52 Example #3: TCP Server (1) /* echo_ser.c This program illustrates an iterative version echo server using TCP Algorithm outline a. Open a TCP socket b. Initialize server socket address structure c. Bind SER_PORT and INADDR_ANY to the open socket (SER_PORT = 49494, an arbitrary number > 49151) d. Create a queue to hold client requests e. Wait for connection request from a client f. Get data from client g. Send response back to client h. Close client connection i. Go back to e. This program also shows: a. How to zero out a structure (bzero()) b. Host to network byte order conversion short (htons()) c. Host to network byte order conversion long (htonl()) d. Use of recv(), which is read() + options Dept. of Computer Science & Engineering 52
53 Example #3: TCP Server (2) e. Use of send(), which is write() + options Be aware that recv() and send() return values of ssize_t To compile: gcc -o echo_ser echo_ser.c Command syntax: echo_ser & */ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #define LISTENQ 5 /* max concurrent client requests allowed */ #define SER_PORT /* arbitrary; official echo server port is 7 */ Dept. of Computer Science & Engineering 53
54 Example #3: TCP Server (3) int main(void) { int ser_sock, cli_sock, ser_len, cli_len; size_t nread; char buf[bufsiz]; struct sockaddr_in ser, cli; /* to open a socket */ if ((ser_sock = socket(af_inet, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "Unable to create server socket\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser socket struct length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* domain Internet */ ser.sin_port = htons(ser_port); /* echo server port */ ser.sin_addr.s_addr = htonl(inaddr_any); /* any IP address accepted */ Dept. of Computer Science & Engineering 54
55 Example #3: TCP Server (4) /* to bind open socket to an IPaddr/service port pair */ if ((bind(ser_sock, (struct sockaddr *)&ser, ser_len)) == -1) { fprintf(stderr, "Unable to bind to service port for server\n"); exit(2); /* to place the socket in passive mode */ if (listen(ser_sock, LISTENQ)) { /* to create a connection request Q */ fprintf(stderr, "Unable to create a client request queue\n"); exit(3); /* listen() does not fail frequent */ /* to wait for connection requests from clients, 1 at a time */ cli_len = sizeof(cli); Dept. of Computer Science & Engineering 55
56 Example #3: TCP Server (5) for (;;) { /* run forever till terminated manually */ cli_sock = accept(ser_sock, (struct sockaddr *)&cli, &cli_len); /* accept() blocks until a client connection request arrives */ if (cli_sock == -1) { fprintf(stderr, "accept() failed\n"); exit(4); if (fork() == 0) { nread = recv(cli_sock, buf, BUFSIZ, 0); /* read from client */ send(cli_sock, buf, nread, 0); /* write back to client */ close(cli_sock); /* close client connection */ exit(0); else close(cli_sock); close(ser_sock); /* close server socket */ return(0); /* currently not reachable */ /* main */ Dept. of Computer Science & Engineering 56
57 Example #3: TCP Client (1) /* echo_cli.c This the client program for echo_ser.c Algorithm outline: a. Open a TCP socket. b. Initialize server socket address structure c. Connect to server d. Send user input to server e. Display server response on screen f. Notify server of intent to close g. Close socket. This program also illustrates: a. Use of gethostbyname() to get some infor. on intended server. b. Use of bcopy() to copy an element into a structure. c. Use of shutdow() to notify server of closing connection. To compile: gcc -o echo_cli echo_cli.c -lsocket -lnsl Command syntax: echo_cli server_name (either DNS or IP) */ Dept. of Computer Science & Engineering 57
58 Example #3: TCP Client (2) #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define SER_PORT /* arbitrary; official echo server port is 7 */ int main(int argc, char *argv[]) { int cli_sock, ser_len, port_number; size_t nread; char buf[bufsiz]; struct sockaddr_in ser; struct hostent *ser_info; Dept. of Computer Science & Engineering 58
59 Example #3: TCP Client (3) /* to open a socket */ if ((cli_sock = socket(af_inet, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "Unable to create socket for client\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* Internet domain */ ser.sin_port = htons(ser_port); /* echo server port number */ if ((ser_info = gethostbyname(argv[1])) == (struct hostent *)NULL) { fprintf(stderr, "unknown server\n"); exit(2); bcopy((char *)ser_info->h_addr, (char *)&ser.sin_addr, ser_info->h_length); /* to connect to server */ Dept. of Computer Science & Engineering 59
60 Example #3: TCP Client (4) if ((connect(cli_sock, (struct sockaddr *)&ser, ser_len)) == -1) { fprintf(stderr, "can't connect to server\n"); exit(3); nread = read(stdin_fileno, buf, BUFSIZ); /* get input from stdin */ send(cli_sock, buf, nread, 0); /* send data to server */ nread = recv(cli_sock, buf, BUFSIZ, 0); /* read back data */ write(stdout_fileno, buf, nread); /* display it on screen */ shutdown(cli_sock, SHUT_RDWR); /* notify server of closing */ close(cli_sock); /* main */ Dept. of Computer Science & Engineering 60
61 More Example #4: UDP Server (1) /* echo_seru.c This program illustrates an iterative version echo server using UDP Algorithm outline a. Open a UDP socket b. Initialize server socket address structure c. Bind SER_PORT and INADDR_ANY to the open socket (SER_PORT = 49495, an arbitrary number > 49151) d. Wait for a datagram from a client e. Send response back to client f. Go back to d. This program also shows: a. How to zero out a structure (bzero()) b. Host to network byte order conversion short (htons()) c. Host to network byte order conversion long (htonl()) d. Use of recv(), which is read() + options e. Use of send(), which is write() + options Be aware that recv() and send() return values of ssize_t Dept. of Computer Science & Engineering 61
62 More Example #4: UDP Server (2) */ To compile: gcc -o echo_seru echo_seru.c -lsocket Command syntax: echo_seru & #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define SER_PORT /* arbitrary; official echo server port is 7 */ int main(void) { int ser_sock, ser_len, cli_len; ssize_t nread; char buf[bufsiz]; struct sockaddr_in ser, cli; Dept. of Computer Science & Engineering 62
63 More Example #4: UDP Server (3) /* to open a socket */ if ((ser_sock = socket(af_inet, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "Unable to create server socket\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser socket struct length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* domain Internet */ ser.sin_port = htons(ser_port); /* echo server port */ ser.sin_addr.s_addr = htonl(inaddr_any); /* any IP address accepted */ /* to bind open socket to an IPaddr/service port pair */ if ((bind(ser_sock, (struct sockaddr *)&ser, ser_len)) == -1) { fprintf(stderr, "Unable to bind to service port for server\n"); exit(2); Dept. of Computer Science & Engineering 63
64 More Example #4: UDP Server (4) /* to wait for datagrams from clients, 1 at a time */ cli_len = sizeof(cli); for (;;) { /* run forever till terminated manually */ nread = recvfrom(ser_sock, buf, BUFSIZ, 0, /* wait for client */ (struct sockaddr *)&cli, &cli_len); if (nread == (ssize_t)-1) { fprintf(stderr, "recvfrom() failed\n"); exit(3); sendto(ser_sock, buf, (size_t)nread, 0, /* echo back to client */ (struct sockaddr *)&cli, cli_len); close(ser_sock); /* close server socket */ return(0); /* currently not reachable */ /* main */ Dept. of Computer Science & Engineering 64
65 More Example #4: UDP Client (1) /* echo_cliu.c This the client program for echo_seru.c Algorithm outline: a. Open a UDP socket. b. Initialize server socket address structure c. Send user input to server d. Display server response on screen e. Close socket. This program also illustrates: a. Use of gethostbyname() to get some infor. on intended server. b. Use of bcopy() to copy an element into a structure. To compile: gcc -o echo_cliu echo_cliu.c -lsocket -lnsl Command syntax: echo_cliu server_name (either DNS or IP) */ Dept. of Computer Science & Engineering 65
66 More Example #4: UDP Client (2) #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #define SER_PORT /* arbitrary; official echo server port is 7 */ int main(int argc, char *argv[]) { int cli_sock, ser_len, port_number; size_t nread; char buf[bufsiz]; struct sockaddr_in ser; struct hostent *ser_info; Dept. of Computer Science & Engineering 66
67 More Example #4: UDP Client (3) /* to open a socket */ if ((cli_sock = socket(af_inet, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "Unable to create socket for client\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* Internet domain */ ser.sin_port = htons(ser_port); /* echo server port number */ if ((ser_info = gethostbyname(argv[1])) == (struct hostent *)NULL) { fprintf(stderr, "unknown server\n"); exit(2); bcopy((char *)ser_info->h_addr, (char *)&ser.sin_addr, ser_info->h_length); Dept. of Computer Science & Engineering 67
68 More Example #4: UDP Client (4) /* to send user input to server */ nread = read(stdin_fileno, buf, BUFSIZ); /* get input from stdin */ nread = sendto(cli_sock, buf, nread, 0, /* send data to server */ (struct sockaddr *)&ser, ser_len); /* to get and display server response */ nread = recvfrom(cli_sock, buf, BUFSIZ, 0, /* get server response */ (struct sockaddr *)&ser, &ser_len); write(stdout_fileno, buf, nread); /* write out to screen */ close(cli_sock); /* main */ Dept. of Computer Science & Engineering 68
69 More Example #5: UDP Server (1) /* forward_ser.c This is a simple server that forwards datagrams between two clients. Algorithm outline a. Open a UDP socket b. Initialize server socket address structure c. Bind SER_PORT and INADDR_ANY to the open socket (SER_PORT = 49499, an arbitrary number > 49151) d. Wait for a datagram from each of the two clients to set up a logical connection. e. Read a datagram from one client and send it to the other client f. go back to e. To compile: gcc -o forward_ser forward_ser.c -lsocket Command syntax: forward_ser & */ Dept. of Computer Science & Engineering 69
70 More Example #5: UDP Server (2) #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #define MAXCLI 2 /* max # of concurrent clients */ #define SER_PORT /* an arbitrary number > */ int main(void) { int i, clino, ser_sock, ser_len, cli_len, maxfdp1; ssize_t nread; char tempbuf[bufsiz], buf[maxcli][bufsiz]; struct sockaddr_in ser, tempaddr, cli[maxcli]; fd_set readset; int bclients(struct sockaddr_in, struct sockaddr_in *), clientno(struct sockaddr_in, struct sockaddr_in *); Dept. of Computer Science & Engineering 70
71 More Example #5: UDP Server (3) /* to open a socket */ if ((ser_sock = socket(af_inet, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "Unable to create server socket\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser socket struct length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* domain Internet */ ser.sin_port = htons(ser_port); /* echo server port */ ser.sin_addr.s_addr = htonl(inaddr_any); /* any IP address accepted */ /* to bind open socket to an IPaddr/service port pair */ if ((bind(ser_sock, (struct sockaddr *)&ser, ser_len)) == -1) { fprintf(stderr, "Unable to bind to service port for server\n"); exit(2); Dept. of Computer Science & Engineering 71
72 More Example #5: UDP Server (4) /* to initialize sockaddr_in structures in the clients array */ for (i = 0; i < MAXCLI; i++) cli[i].sin_addr.s_addr = 0; /* to wait for the first datagram from each client */ cli_len = sizeof(tempaddr); while (1) { nread = recvfrom(ser_sock, tempbuf, BUFSIZ, 0, /* wait for a client */ (struct sockaddr *)&tempaddr, &cli_len); if (nread == (ssize_t)-1) { fprintf(stderr, "recvfrom() failed\n"); exit(3); clino = bclients(tempaddr, cli); strncpy(buf[clientno(tempaddr, cli)], tempbuf, (size_t)nread);/*memcpy() BUG*/ if (clino == MAXCLI) break; Dept. of Computer Science & Engineering 72
73 More Example #5: UDP Server (5) /* to forward initial datagrams between clients */ for (i = 0; i < MAXCLI; i++) { sendto(ser_sock, buf[i], strlen(buf[i]), 0, /* send to another client */ (struct sockaddr *)&cli[(i+1)%2], cli_len); /* to forward datagrams between clients - an infinite loop!! */ while (1) { for (i = 0; i < MAXCLI; i++) { nread = recvfrom(ser_sock, tempbuf, BUFSIZ, MSG_PEEK, /* peek only */ (struct sockaddr *)&tempaddr, &cli_len); if (nread > 0) { nread = recvfrom(ser_sock, tempbuf, BUFSIZ, 0, /* a real read */ (struct sockaddr *)&tempaddr, &cli_len); clino = clientno(tempaddr, cli); /* which client? */ sendto(ser_sock, tempbuf, (size_t)nread, 0, /* forwarding */ (struct sockaddr *)&cli[(clino+1)%2], cli_len); Dept. of Computer Science & Engineering 73
74 More Example #5: UDP Server (6) close(ser_sock); /* close server socket */ return(0); /* currently not reachable */ /* main */ /* bclients() is used to build an array of clients based on their IP addrs */ int bclients(struct sockaddr_in cli, struct sockaddr_in *cliary) { int i; for (i = 0; i < MAXCLI; i++) { if (cliary[i].sin_addr.s_addr!= 0) { if (cli.sin_addr.s_addr == cliary[i].sin_addr.s_addr) continue; /* skip */ else { cliary[i] = cli; /* copy cli infor over */ return(i+1); /* return no of clients */ Dept. of Computer Science & Engineering 74
75 More Example #5: UDP Server (7) return(i); /* return no of clients */ /* bclients */ /* clientno() is used to return the client number for a given IP addr */ int clientno(struct sockaddr_in cli, struct sockaddr_in *cliary) { int i; for (i = 0; i < MAXCLI; i++) { if (cli.sin_addr.s_addr == cliary[i].sin_addr.s_addr) break; return(i); /* clientno */ Dept. of Computer Science & Engineering 75
76 More Example #5: UDP Client (1) /* forward_cli.c This the client program for forward_ser.c Algorithm outline: a. Open a UDP socket. b. Initialize server socket address structure c. Get filename from user, open it for read, and send filename to server d. Wait for server to send filename from another client e. Get ready to use select() f. Use select() to see which fd is ready for read/write g. go back to f until no more fd is ready, or timeout h. Close socket. To compile: gcc -o forward_cli forward_cli.c -lsocket -lnsl Command syntax: forward_cli server_name (either DNS or IP) */ Dept. of Computer Science & Engineering 76
77 More Example #5: UDP Client (2) #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <sys/select.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/time.h> #include <netinet/in.h> #include <netdb.h> #define max(a1, a2) (a1 >= a2? a1 : a2) #define SER_PORT int main(int argc, char *argv[]) { int cli_sock, ser_len, port_number; int res, rfd, maxfdp1; size_t nread; fd_set readset; Dept. of Computer Science & Engineering 77
78 More Example #5: UDP Client (3) char buf[bufsiz], filename[bufsiz]; struct sockaddr_in ser; struct hostent *ser_info; struct timeval timeout; fd_set saverset; /* to open a socket */ if ((cli_sock = socket(af_inet, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "Unable to create socket for client\n"); exit(1); /* to initialize server sockaddr_in structure */ ser_len = sizeof(ser); /* to get ser length */ bzero((char *)&ser, ser_len); /* to zero out struct */ ser.sin_family = AF_INET; /* Internet domain */ ser.sin_port = htons(ser_port); /* echo server port number */ if ((ser_info = gethostbyname(argv[1])) == (struct hostent *)NULL) { fprintf(stderr, "unknown server\n"); exit(2); Dept. of Computer Science & Engineering 78
79 More Example #5: UDP Client (4) bcopy((char *)ser_info->h_addr, (char *)&ser.sin_addr, ser_info->h_length); /* to get filename, open it, and send filename to server */ nread = read(stdin_fileno, buf, BUFSIZ); /* get filename from stdin */ strncpy(filename, buf, nread); filename[nread-1] = '\0'; /* remove '\n' & end with '\0' */ if ((rfd = open(filename, O_RDONLY)) == -1) { fprintf(stderr, "Can't open file\n"); exit(3); sendto(cli_sock, buf, nread, 0, (struct sockaddr *)&ser, ser_len); nread = recvfrom(cli_sock, buf, BUFSIZ, 0, (struct sockaddr *)&ser, &ser_len); write(stdout_fileno, buf, nread); /* write out to screen */ /* to get ready for test for read using select() */ FD_ZERO(&readset); /* clear all bits in readset */ FD_SET(rfd, &readset); /* turn on bit for rfd in readset */ FD_SET(cli_sock, &readset); /* turn on bit for cli_sock */ Dept. of Computer Science & Engineering 79
80 More Example #5: UDP Client (5) maxfdp1 = max(rfd, cli_sock) + 1; /* get the max number of fd's */ timeout.tv_sec = 60; /* max wait 60 sec */ /* to start read/send using select() */ saverset = readset; while (1) { if (res = select(maxfdp1, &readset, NULL, NULL, &timeout)) { if (res == -1) { perror("select() failed"); break; /* error */ if (FD_ISSET(cli_sock, &readset)) { /* socket is readable */ nread = recvfrom(cli_sock, buf, BUFSIZ, 0, (struct sockaddr *)&ser, &ser_len); write(stdout_fileno, buf, nread); /* write out to screen */ if (FD_ISSET(rfd, &readset)) { /* more data in file */ nread = read(rfd, buf, BUFSIZ); /* get data from file */ Dept. of Computer Science & Engineering 80
81 More Example #5: UDP Client (6) if (nread == 0) { close(rfd); /* must close */ FD_CLR(rfd, &saverset); /* remove it from read */ else sendto(cli_sock, buf, nread, 0, /* send to server */ (struct sockaddr *)&ser, ser_len); else break; /* exit infinite loop on tiemout */ readset = saverset; /* to reset it */ close(cli_sock); /* main */ Dept. of Computer Science & Engineering 81
82 Home Work #4 Write a simple file server and client using SOCK_STREAM protocol Client : request a file that it want to copy on Server : search a file and transfer the file to the client server Request a file send the file client Dept. of Computer Science & Engineering 82
Hyo-bong Son Computer Systems Laboratory Sungkyunkwan University
Sockets Hyo-bong Son (proshb@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Client-Server Model Most network application is based on the client-server model: A server
More informationSocket Programming. CSIS0234A Computer and Communication Networks. Socket Programming in C
1 CSIS0234A Computer and Communication Networks Socket Programming in C References Beej's Guide to Network Programming Official homepage: http://beej.us/guide/bgnet/ Local mirror http://www.cs.hku.hk/~c0234a/bgnet/
More informationOral. Total. Dated Sign (2) (5) (3) (2)
R N Oral Total Dated Sign (2) (5) (3) (2) Assignment Group- A_07 Problem Definition Write a program using TCP socket for wired network for following Say Hello to Each other ( For all students) File transfer
More informationSockets. 1 Introduction. (Reference:, Gray Chapter 10) Network Programming Lecture Notes by. Turhan TUNALI
Sockets (Reference:, Gray Chapter 10) Network Programming Lecture Notes by 1 Introduction Turhan TUNALI Unix uses a common interface for the access of files and devices that reside on a single host. The
More informationSockets. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University
Sockets Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Internet Connections (1) Connection Clients and servers communicate by sending streams of
More informationUnix Network Programming
Introduction to Computer Networks Polly Huang EE NTU Unix Network Programming The socket struct and data handling System calls Based on Beej's Guide to Network Programming 1 The Unix Socket A file descriptor
More informationProcesses communicating. Network Communication. Sockets. Addressing processes 4/15/2013
Processes communicating Network Communication Process: program running within a host. within same host, two processes communicate using inter-process communication (defined by OS). processes in different
More informationChapter 6. The Transport Layer. Transport Layer 3-1
Chapter 6 The Transport Layer Transport Layer 3-1 Transport services and protocols provide logical communication between app processes running on different hosts transport protocols run in end systems
More informationProgramming with TCP/IP. Ram Dantu
1 Programming with TCP/IP Ram Dantu 2 Client Server Computing Although the Internet provides a basic communication service, the protocol software cannot initiate contact with, or accept contact from, a
More informationOutline. Distributed Computer Systems. Socket Basics An end-point for a IP network connection. Ports. Sockets and the OS. Transport Layer.
Outline Distributed Computer Systems Socket basics Socket details (TCP and UDP) Socket options Final notes Sockets Socket Basics An end-point for a IP network connection what the application layer plugs
More informationPA #2 Reviews. set_name, get_name, del_name. Questions? Will be modified after PA #4 ~
Sockets Prof. Jin-Soo Kim( jinsookim@skku.edu) TA Dong-Yun Lee(dylee@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu PA #2 Reviews set_name, get_name, del_name Will
More informationIntroduction to Socket Programming
UNIT II - ELEMENTARY TCP SOCKETS Introduction to Socket Programming Introduction to Sockets Socket address Structures Byte ordering functions address conversion functions Elementary TCP Sockets socket,
More informationSockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.
1 Sockets Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Internet Connections (1) 2 Connection Clients and servers communicate by sending streams of bytes over
More informationTCP: Three-way handshake
Sockets in C 1 Sockets in C The slides by themselves will not be sufficient to learn how to write socket code. If you did not attend class, then you will want to review the relevant chapters in Kerrisk
More informationOutline. Operating Systems. Socket Basics An end-point for a IP network connection. Ports. Network Communication. Sockets and the OS
Outline Operating Systems Socket basics Socket details Socket options Final notes Project 3 Sockets Socket Basics An end-point for a IP network connection what the application layer plugs into programmer
More informationOutline. Distributed Computing Systems. Socket Basics (1 of 2) Socket Basics (2 of 2) 3/28/2014
Outline Distributed Computing Systems Sockets Socket basics Socket details (TCP and UDP) Socket options Final notes Socket Basics (1 of 2) An end-point for an Internet network connection what application
More informationCS 640: Computer Networking
CS 640: Computer Networking Yu-Chi Lai Lecture 3 Network Programming Topics Client-server model Sockets interface Socket primitives Example code for echoclient and echoserver Debugging With GDB Programming
More informationsottotitolo Socket Programming Milano, XX mese 20XX A.A. 2016/17 Federico Reghenzani
Titolo presentazione Piattaforme Software per la Rete sottotitolo Socket Programming Milano, XX mese 20XX A.A. 2016/17 Outline 1) Introduction to Sockets 2) UDP communication 3) TCP communication 4) RAW
More informationSocket Programming for TCP and UDP
CSCI4430 Data Communication and Computer Networks Socket Programming for TCP and UDP ZHANG, Mi Jan. 19, 2017 Outline Socket Programming for TCP Introduction What is TCP What is socket TCP socket programming
More informationNetwork Communication
Network Communication Processes communicating Process: program running within a host. q within same host, two processes communicate using inter- process communica6on (defined by OS). q processes in different
More informationTutorial on Socket Programming
Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Hao Wang (Slides are mainly from Seyed Hossein Mortazavi, Monia Ghobadi, and Amin Tootoonchian, ) 1 Outline Client-server
More informationCSC209H Lecture 9. Dan Zingaro. March 11, 2015
CSC209H Lecture 9 Dan Zingaro March 11, 2015 Socket Programming (Kerrisk Ch 56, 57, 59) Pipes and signals are only useful for processes communicating on the same machine Sockets are a general interprocess
More informationGroup-A Assignment No. 6
Group-A Assignment No. 6 R N Oral Total Dated Sign (2) (5) (3) (10) Title : File Transfer using TCP Socket Problem Definition: Use Python for Socket Programming to connect two or more PCs to share a text
More informationHow do we Communicate? Introduction to Unix Network Programming. What does Alice do? What does Bob do? Two simplest networking programs
Introduction to Unix Network Programming Reference: Stevens Unix Network Programming How do we Communicate? Send a mail from Alice to Bob Bob Alice in Champaign, Bob in Hollywood Example: US Postal Service
More informationSystem Programming. Sockets
Content : by Dr. B. Boufama School of Computer Science University of Windsor Instructor: Dr. A. Habed adlane@cs.uwindsor.ca http://cs.uwindsor.ca/ adlane/60-256 Content Content 1 Introducing 2 3 Internet
More informationCS 3516: Computer Networks
Welcome to CS 3516: Prof. Yanhua Li Time: 9:00am 9:50am M, T, R, and F Location: AK219 Fall 2018 A-term 1 Some slides are originally from the course materials of the textbook Computer Networking: A Top
More informationNetwork Socket Programming - 3 BUPT/QMUL
Network Socket Programming - 3 BUPT/QMUL 2018-04-02 Agenda Basic concepts in NP Introduction to IP & TCP/UDP Introduction to Sockets 2 Introduction to Sockets Reviews of some helpful points Sockets interface
More informationNetwork Socket Programming - 3 BUPT/QMUL
Network Socket Programming - 3 BUPT/QMUL 2017-3-27 Agenda Basic concepts in NP Introduction to IP & TCP/UDP Introduction to Sockets 2 Introduction to Sockets Reviews of some helpful points Sockets interface
More informationSocket Programming TCP UDP
Socket Programming TCP UDP Introduction Computer Network hosts, routers, communication channels Hosts run applications Routers forward information Packets: sequence of bytes contain control information
More informationThe BSD UNIX Socket Interface (CS 640 Lecture) Assignment 1. Interprocess Communication (IPC) Work Individually (no groups)
The BSD UNIX Socket Interface (CS 640 Lecture) Assignment 1 Work Individually (no groups) Due Date: in class, Monday, September 19 Robert T Olsen olsen@cswiscedu 7390CS Office Hours: 3-5T, 11-12F - exception
More informationDepartment of Computer Science
Department of Computer Science Notes on Interprocess Communication in Unix Jean Dollimore,Oct.1990, last revised Feb. 1996 These notes explain how you can write "distributed programs" in C or C++ running
More informationApplication Programming Interfaces
Application Programming Interfaces Stefan D. Bruda Winter 2018 SYSTEM CALLS Machine 1 Machine 2 Application 1 Application 3 Application 4 Application 5 Application 2 API (system functions) API (system
More informationNetwork Programming in C: The Berkeley Sockets API. Networked Systems 3 Laboratory Sessions
Network Programming in C: The Berkeley Sockets API Networked Systems 3 Laboratory Sessions The Berkeley Sockets API Widely used low-level C networking API First introduced in 4.3BSD Unix Now available
More informationCS118 Discussion 1B, Week 1. Taqi Raza BUNCHE 1209B, Fridays 12:00pm to 1:50pm
CS118 Discussion 1B, Week 1 Taqi Raza BUNCHE 1209B, Fridays 12:00pm to 1:50pm 1 TA Taqi, PhD student in Computer Networking Discussion (1B): Bunche 1209, Fri 12:00 1:50 p.m. Office hours: Boelter Hall
More informationNETWORK PROGRAMMING. Instructor: Junaid Tariq, Lecturer, Department of Computer Science
NETWORK PROGRAMMING CSC- 341 25 Instructor: Junaid Tariq, Lecturer, Department of Computer Science 26 9 Lecture Sockets as means for inter-process communication (IPC) application layer Client Process Socket
More informationPorts under 1024 are often considered special, and usually require special OS privileges to use.
1 2 Turns out that besides an IP address (used by the IP layer), there is another address that is used by TCP (stream sockets) and, coincidentally, by UDP (datagram sockets). It is the port number. It's
More informationReview. Preview. Closing a TCP Connection. Closing a TCP Connection. Port Numbers 11/27/2017. Packet Exchange for TCP Connection
Review Preview Algorithms and Issues in Client Software Design Client Architecture Identifying the Location of a Parsing an Address Argument Looking Up a Domain Name Looking Up a Well-Known Port by Name
More informationSTUDY OF SOCKET PROGRAMMING
STUDY OF SOCKET PROGRAMMING Sockets : An application programming interface(api) used for inter process communication. Sockets allow communication between two different processes on the same or different
More informationNETWORK AND SYSTEM PROGRAMMING
NETWORK AND SYSTEM PROGRAMMING LAB 09 Network Byte Ordering, inet_aton, inet_addr, inet_ntoa Functions Objectives: To learn byte order conversion To understand inet-aton, inet_addr, inet_ntoa Functions
More informationNetwork Programming Worksheet 2. Simple TCP Clients and Servers on *nix with C.
Simple TCP Clients and Servers on *nix with C. Aims. This worksheet introduces a simple client and a simple server to experiment with a daytime service. It shows how telnet can be used to test the server.
More informationUNIT IV- SOCKETS Part A
1. Define sockets - SOCKETS Part A A socket is a construct to provide a communication between computers. It hides the underlying networking concepts and provides us with an interface to communicate between
More informationLecture 7. Followup. Review. Communication Interface. Socket Communication. Client-Server Model. Socket Programming January 28, 2005
Followup symbolic link (soft link): pathname, can be across file systems, replacement of file will be active on all symbolic links, consumes at least an inode. hard link: pointers to an inode, only in
More informationSockets. Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University Embedded Software Lab.
1 Sockets Dong-kun Shin Embedded Software Laboratory Sungkyunkwan University http://nyx.skku.ac.kr Echo Client (1) 2 #include #include #include #include
More informationWinSock. What Is Sockets What Is Windows Sockets What Are Its Benefits Architecture of Windows Sockets Network Application Mechanics
WinSock What Is Sockets What Is Windows Sockets What Are Its Benefits Architecture of Windows Sockets Network Application Mechanics What Is Sockets Standard API (Application Programming Interface) for
More informationClient-server model The course that gives CMU its Zip! Network programming Nov 27, Using ports to identify services.
15-213 The course that gives CMU its Zip! Network programming Nov 27, 2001 Topics Client- model Sockets interface Echo and Client- model Every network application is based on the - model: Application is
More informationSockets. UNIX-style IPC. Silberschatz, Galvin and Gagne 2005 Msc. Ivan A. Escobar Broitman 2007
UNIX-style IPC Silberschatz, Galvin and Gagne 2005 Msc. Ivan A. Escobar Broitman 2007 Introduction to A socket is one of the most fundamental technologies of computer networking. The socket is the BSD
More informationThe Berkeley Sockets API. Networked Systems Architecture 3 Lecture 4
The Berkeley Sockets API Networked Systems Architecture 3 Lecture 4 The Berkeley Sockets API Widely used low-level C networking API First introduced in 4.3BSD Unix Now available on most platforms: Linux,
More informationCS4700/CS5700 Fundamentals of Computer Networking
CS4700/CS5700 Fundamentals of Computer Networking Prof. Alan Mislove Lecture 3: Crash course in socket programming September 10th, 2009 Project 0 Goal: Familiarize you with socket programming in C Implement
More informationNetwork programming(i) Lenuta Alboaie
Network programming(i) Lenuta Alboaie adria@info.uaic.ro 2017 2018 Computer Network http://www.info.uaic.ro/~computernetworks 1 Content Client/server paradigm API for network programming BSD Socket Characteristics
More informationCommunication. Sockets (Haviland Ch. 10)
Communication Sockets (Haviland Ch. 10) 1 Simple Web Request 5LFKDUG V+RPH3DJH &RXUVHV 5HVHDUFK 2 How do we find the server? Every computer on the Internet has an Internet address. Called an IP address
More informationMSc Integrated Electronics Networks Assignment. Investigation of TCP/IP Sockets and Ports. Gavin Cameron
MSc Integrated Electronics Networks Assignment Investigation of TCP/IP Sockets and Ports Gavin Cameron Introduction TCP and IP (Transmission Control Protocol / Internet Protocol) are two protocols from
More informationUNIX Sockets. Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E.
UNIX Sockets Developed for the Azera Group By: Joseph D. Fournier B.Sc.E.E., M.Sc.E.E. Socket and Process Communication application layer User Process Socket transport layer (TCP/UDP) network layer (IP)
More informationSocket Programming 2007/03/28
Socket Programming 2007/03/28 Reference W. Richard Stevens, Unix Network Programming 2/e Volume 1,1998 James F. Kurose and Keith W. Ross, "Computer Networks: A Top-Down Approach Featuring the Internet
More informationLecture 3 Overview! Last Lecture! TCP/UDP and Sockets introduction!
Lecture 3 Overview! Last Lecture! TCP/UDP and Sockets introduction! This Lecture! Elementary TCP sockets! TCP Client-Server example! Source: Stevens book(chapters 4,5), Comer s book (Chapters 20, 21)!
More informationElementary TCP Sockets
Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens Distributed Computer Systems 1 socket interface Application 1 Application 2 socket interface user kernel user kernel
More informationA. Basic Function Calls for Network Communications
IV. Network Programming A. Basic Function Calls for Network Communications 1 B. Settings for Windows Platform (1) Visual C++ 2008 Express Edition (free version) 2 (2) Winsock Header and Libraries Include
More informationNetwork Programming in C. Networked Systems 3 Laboratory Sessions and Problem Sets
Network Programming in C Networked Systems 3 Laboratory Sessions and Problem Sets Lab Timetable, Aims, and Objectives Teaching Week Activity 14 Introduction 15 Warm-up exercise 16 17 Web client 18 19 20
More informationHybrid of client-server and P2P. Pure P2P Architecture. App-layer Protocols. Communicating Processes. Transport Service Requirements
Announcements CS 5565 Network Architecture and Protocols Lecture 5 Godmar Back Problem Set 1 due Feb 17 Project 1 handed out shortly 2 Layer The Layer Let s look at some s (in keeping with top-down) architectures:
More informationCS321: Computer Networks Socket Programming
CS321: Computer Networks Socket Programming Dr. Manas Khatua Assistant Professor Dept. of CSE IIT Jodhpur E-mail: manaskhatua@iitj.ac.in Socket Programming It shows how the network application programs
More informationLab 0. Yvan Petillot. Networks - Lab 0 1
Lab 0 Yvan Petillot Networks - Lab 0 1 What You Will Do In This Lab. The purpose of this lab is to help you become familiar with the UNIX/LINUX on the lab network. This means being able to do editing,
More informationCS 43: Computer Networks. 05: Socket Programming September 12-14, 2018
CS 43: Computer Networks 05: Socket Programming September 12-14, 2018 Reading Quiz Lecture 5/6 - Slide 2 Socket Programming Adapted from: Donahoo, Michael J., and Kenneth L. Calvert. TCP/IP sockets in
More informationCSE 124 Discussion Section Sockets Programming 10/10/17
CSE 124 Discussion Section Sockets Programming 10/10/17 Topics What s a socket? Creating a socket Connecting a socket Sending data Receiving data Resolving URLs to IPs Advanced socket options Live code
More informationEEC-484/584 Computer Networks
EEC-484/584 Computer Networks Lecture 15 wenbing@ieee.org (Lecture nodes are based on materials supplied by Dr. Louise Moser at UCSB and Prentice-Hall) Outline 2 Review of last lecture The network layer
More informationCSE 333 SECTION 8. Sockets, Network Programming
CSE 333 SECTION 8 Sockets, Network Programming Overview Domain Name Service (DNS) Client side network programming steps and calls Server side network programming steps and calls dig and ncat tools Network
More informationSocket Programming(2/2)
Socket Programming(2/2) 1 Outline 1. Introduction to Network Programming 2. Network Architecture Client/Server Model 3. TCP Socket Programming 4. UDP Socket Programming 5. IPv4/IPv6 Programming Migration
More informationCLIENT-SIDE PROGRAMMING
CLIENT-SIDE PROGRAMMING George Porter Apr 11, 2018 ATTRIBUTION These slides are released under an Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0) Creative Commons license These slides
More informationNetwork Programming November 3, 2008
15-213 Network Programming November 3, 2008 Topics Programmer s view of the Internet (review) Sockets interface Writing clients and servers class20.ppt A Client-Server Transaction Most network applications
More informationCS321: Computer Networks Introduction to Application Layer
CS321: Computer Networks Introduction to Application Layer Dr. Manas Khatua Assistant Professor Dept. of CSE IIT Jodhpur E-mail: manaskhatua@iitj.ac.in Basic Application layer provides services to the
More informationICT 6544 Distributed Systems Lecture 5
ICT 6544 Distributed Systems Lecture 5 Hossen Asiful Mustafa Message Brokers Figure 4-21. The general organization of a message broker in a message-queuing system. IBM s WebSphere Message-Queuing System
More informationSystems software design NETWORK COMMUNICATIONS & RPC SYSTEMS
Systems software design NETWORK COMMUNICATIONS & RPC SYSTEMS outline network programming BSD/POSIX Socket API RPC systems object-oriented bridges CORBA DCOM RMI WebServices WSDL/SOAP XML-RPC REST network
More informationThe User Datagram Protocol
The User Datagram Protocol Stefan D. Bruda Winter 2018 UDP Very similar to the TCP in terms of API Dissimilar with TCP in terms of innards (and hence programming techniques) Many-to-many communication.
More informationPiotr Mielecki Ph. D.
Piotr Mielecki Ph. D. http://mielecki.ristel.pl/ piotr.mielecki@pwr.edu.pl pmielecki@gmail.com Building blocks of client-server applications: Client, Server, Middleware. Simple client-server application:
More informationA Socket Example. Haris Andrianakis & Angelos Stavrou George Mason University
A Socket Example & George Mason University Everything is a file descriptor Most socket system calls operate on file descriptors Server - Quick view socket() bind() listen() accept() send(), recv() close()
More informationA Quick Guide to Networking Software by J. Sanguino 2 nd Edition: February 2010
A Quick Guide to Networking Software by J. Sanguino 2 nd Edition: February 2010 IST - Computer Networks 2009/2010 Welcome, you are inside now. 1 st Task: Get the host name! You have 10 minutes. gethostname
More informationCS307 Operating Systems Processes
CS307 Processes Fan Wu Department of Computer Science and Engineering Shanghai Jiao Tong University Spring 2018 Process Concept Process a program in execution An operating system executes a variety of
More informationProcesses. Process Concept. The Process. The Process (Cont.) Process Control Block (PCB) Process State
CS307 Process Concept Process a program in execution Processes An operating system executes a variety of programs: Batch system jobs Time-shared systems user programs or tasks All these activities are
More informationUNIX Network Programming. Overview of Socket API Network Programming Basics
UNIX Network Programming Overview of Socket API Network Programming Basics 1 Client-Server Model Client Machine A Network Server Machine B Web browser and server FTP client and server Telnet client and
More informationTypes (Protocols) Associated functions Styles We will look at using sockets in C Java sockets are conceptually quite similar
Socket Programming What is a socket? Using sockets Types (Protocols) Associated functions Styles We will look at using sockets in C Java sockets are conceptually quite similar - Advanced Data Communications:
More informationUDP CONNECT TO A SERVER
UDP The User Datagram Protocol Stefan D. Bruda Winter 2018 Very similar to the TCP in terms of API Dissimilar with TCP in terms of innards (and hence programming techniques) Many-to-many communication.
More informationLecture 7. Berkeley Socket Programming
Lecture 7 Berkeley Socket Programming Berkeley Sockets Unix Socket Programming FAQ Beej's Guide to Network Programming Metaphors Postal Service Address Name, Street, City, State, Zip Code Return Address
More informationCSE 333 SECTION 7. C++ Virtual Functions and Client-Side Network Programming
CSE 333 SECTION 7 C++ Virtual Functions and Client-Side Network Programming Overview Virtual functions summary and worksheet Domain Name Service (DNS) Client side network programming steps and calls dig
More informationOverview. Administrative. * HW# 5 Due next week. * HW# 5 : Any Questions. Topics. * Client Server Communication. * 12.
Overview Administrative * HW# 5 Due next week * HW# 5 : Any Questions Topics * Client Server Communication * 12.3 ISO/OSI Layers * 12.4 UICI Implementations * App. B (UICI : Socket Implementation) * 12.4
More informationSOCKETS. COMP750 Distributed Systems
SOCKETS COMP750 Distributed Systems Sockets The Socket library is a traditional Application Program Interface (API) to the transport layer. Sockets were originally implemented in Unix systems and have
More informationCSE 333 SECTION 7. Client-Side Network Programming
CSE 333 SECTION 7 Client-Side Network Programming Overview Domain Name Service (DNS) Client side network programming steps and calls dig and ncat tools Network programming for the client side Recall the
More informationInternet protocol stack. Internetworking II: Network programming. April 20, UDP vs TCP. Berkeley Sockets Interface.
15-213 Internetworking II: Network programming Berkeley sockets interface Internet protocol stack April 20, 2000 Topics client/server model Berkeley sockets TCP client and server examples UDP client and
More informationIntroduction to Network Programming using C/C++
Introduction to Network Programming using C/C++ Slides mostly prepared by Joerg Ott (TKK) and Olaf Bergmann (Uni Bremen TZI) 1 Would be giving brief introduction on... Parsing Command line Socket Related
More informationInternetworking II: Network programming. April 20, 2000
15-213 Internetworking II: Network programming Topics April 20, 2000 client/server model Berkeley sockets TCP client and server examples UDP client and server examples I/O multiplexing with select() Internet
More informationECE 435 Network Engineering Lecture 2
ECE 435 Network Engineering Lecture 2 Vince Weaver http://web.eece.maine.edu/~vweaver vincent.weaver@maine.edu 6 September 2018 Announcements Homework 1 will be posted. Will be on website, will announce
More informationNetwork Programming and Protocl Design. Nixu Ltd.
Network Programming and Protocl Design Nixu Ltd. What is a socket? Sockets (also known as Berkeley Sockets) is an application programming interface (API) to the operating system s TCP/IP stack Used on
More informationIntroduction to Socket Programming
Introduction to Socket Programming (Advanced Computer Networks) By Priyank Shah NET ID : pss160530 A Simple Question What are Sockets? Sockets are communication points on the same or different computers
More informationChristian Tschudin (basierend auf einem Foliensatz von C. Jelger und T. Meyer) Departement Mathematik und Informatik, Universität Basel
Internettechnologien (CS262) Socket Programming in C 4. März 2015 Christian Tschudin (basierend auf einem Foliensatz von C. Jelger und T. Meyer) Departement Mathematik und Informatik, Universität Basel
More informationContext. Distributed Systems: Sockets Programming. Alberto Bosio, Associate Professor UM Microelectronic Departement
Distributed Systems: Sockets Programming Alberto Bosio, Associate Professor UM Microelectronic Departement bosio@lirmm.fr Context Computer Network hosts, routers, communication channels Hosts run applications
More informationInterprocess Communication Mechanisms
Interprocess Communication 1 Interprocess Communication Mechanisms shared storage These mechanisms have already been covered. examples: shared virtual memory shared files processes must agree on a name
More informationTCP/IP Sockets in C: Practical Guide for Programmers. Computer Chat. Internet Protocol (IP) IP Address. Transport Protocols. Ports
TCP/IP Sockets in C: Practical Guide for Programmers Computer Chat! How do we make computers talk? Michael J. Donahoo Kenneth L. Calvert Morgan Kaufmann Publisher $14.95 Paperback! How are they interconnected?
More informationUnix Network Programming Chapter 4. Elementary TCP Sockets 광운대학교컴퓨터과학과 정보통신연구실 석사과정안중현
Unix Network Programming Chapter 4. Elementary TCP Sockets 광운대학교컴퓨터과학과 정보통신연구실 석사과정안중현 4.1 Introduction A Time line of the typical scenario that takes place between a TCP client and server. Describes the
More informationTopics for this Week
Topics for this Week Layered Network Architecture ISO/OSI Reference Model Internet Protocol Suite Overview Application Programming Interface BSD Socket API Readings Sections 1.1-1.5, 6.1.3 (socket programming),
More informationInterprocess Communication Mechanisms
Interprocess Communication 1 Interprocess Communication Mechanisms ffl shared storage These mechanisms have already been covered. examples: Λ shared virtual memory Λ shared files processes must agree on
More informationUNIX Sockets. COS 461 Precept 1
UNIX Sockets COS 461 Precept 1 Socket and Process Communica;on application layer User Process Socket transport layer (TCP/UDP) OS network stack network layer (IP) link layer (e.g. ethernet) Internet Internet
More informationTCP Network Programming in C
CPSC 360 Network Programming TCP Network Programming in C Michele Weigle Department of Computer Science Clemson University mweigle@cs.clemson.edu http://www.cs.clemson.edu/~mweigle/courses/cpsc360 1 Sockets
More information