Network and Sockets Today: Get started doing network programming Reliable socket programming Aka TCP programming
setup A number of PCs running XP and cygwin (tested) Vista/W7 and cygwin (not ! tested) Linux/ubuntu/... (tested) Mac OSX (not tested but …) Or linux livecd on PC (tested) Why ? Because !
How ? Short !!! lecture Back and programming !!! :-) You can only programming by programming !
A TCP socket is A reliable connection You get data correct transferred Or not valid data through No size limit of data – you can “stream” a movie Although size of buffers matters A unreliable link is a UDP socket Unreliable – no check on data and on if they were received ok 64 B limit on each transaction (read/write)
TCP – the reliable one
UDP socket – the unreliable
Compared to … files file_handle = fopen (“jens”,..) write(file_handle,” ost\n”); read(file_handle,...) Etc /* so close to file operations ! */
Sockit ;-) fgets(buffer,255,stdin); n = write(sockfd,buffer,strlen(buffer)); if (n < 0) error("ERROR writing to socket"); bzero(buffer,256); n = read(sockfd,buffer,255);
Server versus client SERVER The server shall be ready to accept a call from a client IS not aware of clients IP address prior to call Server and client must agree on ping pong protocol Normally at design stage ! Server may be able to handle more than one call at a time (call desk :-)
Server versus client CLIENT Try to connect to a server Must know server IP and port(1..65535) Your server should use ports above 10000 Some ports: (from /etc/services) finger 79/tcp www 80/tcp http www 80/udp link 87/tcp ttylink kerberos 88/tcp kerberos5 krb5 kerberos 88/udp kerberos5 krb5
int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept");
if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s\n",buffer); n = write(newsockfd,"I got your message",18);