Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm two types of transport service via socket API: unreliable datagram reliable, byte stream-oriented socket a host-local, application-created, OS-controlled interface (a “door”) into which application process can both send and receive messages to/from another application process 2: Application Layer 1 Socket-programming using TCP Socket: a door between application process and end-endtransport protocol (UCP or TCP) TCP service: reliable transfer of bytes from one process to another controlled by application developer controlled by operating system process process socket TCP with buffers, variables host or server internet socket TCP with buffers, variables controlled by application developer controlled by operating system host or server 2: Application Layer 2 Socket programming with TCP Client must contact server server process must first be running server must have created socket (door) that welcomes client’s contact Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP When contacted by client, server TCP creates new socket for server process to communicate with client allows server to talk with multiple clients source port numbers used to distinguish clients (more in Chap 3) application viewpoint TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server 2: Application Layer 3 Stream jargon A stream is a sequence of characters that flow into or out of a process. An input stream is attached to some input source for the process, eg, keyboard or socket. An output stream is attached to an output source, eg, monitor or socket. 2: Application Layer 4 Socket programming with TCP keyboard monitor output stream inFromServer 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket (inFromServer stream) Client Process process input stream outToServer 1) client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream) inFromUser Example client-server app: input stream client TCP clientSocket socket to network TCP socket from network 2: Application Layer 5 Client/server socket interaction: TCP Server (running on hostid) Client create socket, port=x, for incoming request: welcomeSocket = ServerSocket() TCP wait for incoming connection request connection connectionSocket = welcomeSocket.accept() read request from connectionSocket write reply to connectionSocket close connectionSocket setup create socket, connect to hostid, port=x clientSocket = Socket() send request using clientSocket read reply from clientSocket close clientSocket 2: Application Layer 6 Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; Create input stream Create client socket, connect to server Create output stream attached to socket BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 2: Application Layer 7 Example: Java client (TCP), cont. Create input stream attached to socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); Send line to server outToServer.writeBytes(sentence + '\n'); Read line from server modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } 2: Application Layer 8 Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 2: Application Layer 9 Example: Java server (TCP), cont Create output stream, attached to socket DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); Read in line from socket clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; Write out line to socket outToClient.writeBytes(capitalizedSentence); } } } End of while loop, loop back and wait for another client connection 2: Application Layer 10 Socket programming with UDP UDP: no “connection” between client and server no handshaking sender explicitly attaches IP address and port of destination to each packet server must extract IP address, port of sender from received packet application viewpoint UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server UDP: transmitted data may be received out of order, or lost 2: Application Layer 11 Client/server socket interaction: UDP Server (running on hostid) create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket write reply to serverSocket specifying client host address, port number Client create socket, clientSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read reply from clientSocket close clientSocket 2: Application Layer 12 Example: Java client (UDP) input stream Client process monitor inFromUser keyboard Process Input: receives packet (TCP received “byte stream”) UDP packet receivePacket packet (TCP sent “byte stream”) sendPacket Output: sends UDP packet client UDP clientSocket socket to network UDP socket from network 2: Application Layer 13 Example: Java client (UDP) import java.io.*; import java.net.*; Create input stream Create client socket Translate hostname to IP address using DNS class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); 2: Application Layer 14 Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); Send datagram to server clientSocket.send(sendPacket); Read datagram from server clientSocket.receive(receivePacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } 2: Application Layer 15 Example: Java server (UDP) import java.io.*; import java.net.*; Create datagram socket at port 9876 class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { Create space for received datagram Receive datagram DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); 2: Application Layer 16 Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); Get IP addr port #, of sender InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); Create datagram to send to client DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); Write out datagram to socket serverSocket.send(sendPacket); } } } End of while loop, loop back and wait for another datagram 2: Application Layer 17 UDP Sockets int socket(int domain, int type, int protocol); int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen); ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sock-addr *from, socklen_t *fromlen); 2: Application Layer 18 UDP Sockets int socket(int domain, int type, int protocol); socket() creates an endpoint for communication and returns a descriptor. Domain: PF_INET PF_INET6 IPv4 Internet protocols IPv6 Internet protocols ip(7) Type: SOCK_STREAM: TCP Sockets SOCK_DGRAM: UDP Sockets Protocol: The protocol specifies a particular protocol to be used with the socket. Normally only a single protocol exists to support a particular socket type within a given protocol family, in which a case protocol can be specified as 0. 2: Application Layer 19 UDP Sockets int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen); Bind() gives the socket sockfd the local address my_addr. my_addr is addrlen bytes long. Setting up the socket addr structure: struct cliAddr; cliAddr.sin_family = AF_INET; cliAddr.sin_addr.s_addr = htonl(INADDR_ANY); cliAddr.sin_port = htons(0); 2: Application Layer 20 UDP Sockets ssize_t sendto(int s, const void *buf, size_t len, int flags, const struct sockaddr *to, socklen_t tolen); s = Socket descriptor buf = Message to send len = Length of message flags = Normally 0, specifies the behavior of the socket to = Pointer to the sockaddr structure that contains the destination (IP and port) • remoteAddr.sin_port • remoteAddr.sin_addr.s_addr tolen = Length of remoteAddr socket 2: Application Layer 21 UDP Sockets ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct sock-addr *from, socklen_t *fromlen); s = Socket descriptor buf = Pointer of buffer of which will be filled by the message. len = The length of the buffer flags = Normally 0, specifies the behavior of the socket from = Pointer to the sockaddr structure that contains the destination (IP and port) • remoteAddr.sin_port • remoteAddr.sin_addr.s_addr fromlen = Length of sockaddr struct 2: Application Layer 22 UDP Client Example #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <string.h> /* memset() */ #include <sys/time.h> /* select() */ #include <stdlib.h> #include <readline/readline.h> #include <readline/history.h> #define REMOTE_SERVER_PORT 1500 //bind to port 1500 #define MAX_MSG 100 int main(int argc, char *argv[]) { int sd, rc, i; struct sockaddr_in cliAddr, remoteServAddr; struct hostent *h; 2: Application Layer 23 /* get server IP address (no check if input is IP address or DNS name */ h = gethostbyname(argv[1]); if(h==NULL) { printf("%s: unknown host '%s' \n", argv[0], argv[1]); exit(1); } printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name, inet_ntoa(*(struct in_addr *)h->h_addr_list[0])); remoteServAddr.sin_family = h->h_addrtype; memcpy((char *) &remoteServAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT); /* socket creation */ sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind any port */ cliAddr.sin_family = AF_INET; /* pick any available network interface */ cliAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* bind to any local port */ cliAddr.sin_port = htons(0); 2: Application Layer 24 rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr)); if(rc<0) { printf("%s: cannot bind port\n", argv[0]); exit(1); } char* line; int sent; /* send data */ while(1){ /* Prompt user for string and send to the server */ line = readline("Enter text: "); sent = sendto(sd, line, strlen(line)+1, 0, (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr)); if(sent<0) { printf("%s: cannot send data\n",line); close(sd); exit(1); } 2: Application Layer 25 char msg[MAX_MSG]; /* receive response from server */ int remoteServSize = sizeof(remoteServAddr); rc = recvfrom(sd,msg,MAX_MSG, 0, (struct sockaddr*) &remoteServAddr, &remoteServSize); if(rc<0){ printf("Error occurred receiving from server\n"); exit(1); } printf("%s\n", msg); } return 1; } 2: Application Layer 26 UDP Server Example #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> /* close() */ #include <string.h> /* memset() */ #include <stdlib.h> #include <string.h> #define LOCAL_SERVER_PORT 1500 /* Listen on port 1500 */ #define MAX_MSG 100 #define MAX_RESPONSE 1024 int main(int argc, char *argv[]) { int sd, rc, n, cliLen; struct sockaddr_in cliAddr, servAddr; char msg[MAX_MSG]; /* socket creation */ sd=socket(AF_INET, SOCK_DGRAM, 0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } 2: Application Layer 27 /* bind local server port */ servAddr.sin_family = AF_INET; /* Accept a connection from interface */ servAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Listen on Port 1500 */ servAddr.sin_port = htons(LOCAL_SERVER_PORT); rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr)); if(rc<0) { printf("%s: cannot bind port number %d \n", argv[0], LOCAL_SERVER_PORT); exit(1); } printf("%s: waiting for data on port UDP %u\n", argv[0],LOCAL_SERVER_PORT); /* server infinite loop */ while(1) { /* init buffer */ memset(msg,0x0,MAX_MSG); /* receive message */ cliLen = sizeof(cliAddr); n = recvfrom(sd, msg, MAX_MSG, 0, (struct sockaddr *) &cliAddr, &cliLen); 2: Application Layer 28 if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } /* print received message */ printf("%s: from %s:UDP%u : %s \n", argv[0],inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port),msg); char response[MAX_RESPONSE]; char* responseMsg = "Received your message: "; int len = strlen(responseMsg) + 1; strcpy(response,responseMsg); strncat(response,msg,MAX_RESPONSE-len); n = sendto(sd, response, strlen(response)+1,0,(struct sockaddr*) &cliAddr, sizeof(cliAddr)); if(n<0){ printf("Error sending to client\n"); exit(1); } }/* end of server infinite loop */ return 0; } 2: Application Layer 29 GDB Basics How to setup the environment to dump core files: csil% ulimit –c unlimited How to open a core file csil% gdb –q ./executable corename (the parameter –q is optional. The will prevent GDB from printing out extra garbage when it initially loads) What to do when a core file is loaded up (gdb) bt (backtrace) • Will show you the stack when the program crashed More useful to run your program with GDB. csil% gdb –q ./executable • Set breakpoints: (gdb) b <line number> OR b <function name> • Run the program: (gdb) r <commandline params> – – – – – The program will break when it reaches a breakpoint Print value of a variable: (gdb) print <variable name> Step through a function: (gdb) s Skip to the next instruction: (gdb) n Continue until the program exits or another breakpoint is reached: (gdb) c 2: Application Layer 30