SLIDE 10 10
Sending and receiving data
ssize_t recv(int sockfd, void *buffer,size_t length, int flags); ssize_t send(int sockfd, void *buffer,size_t length, int flags);
Full duplex communication Normally, set flags to 0 (this makes recv,send identical to
read, write)
recv returns 0 (end of file) when the other end is dead
(through a close)
Remember to close() the connection when done
Server side
//socket initialized as shown earlier while(1) { //accept connection if((newsockfd=accept(sockfd,NULL,NULL)) == -1) { //handle error } //spawn a child to deal with the connection if(fork()==0){ while(recv(newsockfd,&c,1,0) > 0) { c=toupper(c); send(newsockfd,&c,1,0); } } }
Byte order
Big-endian Little-endian Intel is little-endian, and Sparc is big-endian 00 01 64 C1 A A+1 A+2 A+3 91,329 = 00 01 64 C1 A+3 A+2 A+1 A 91,329 =
Network byte order
To communicate between machines with
unknown or different “endian-ness” we convert numbers to network byte order (big- endian) before we send them.
There are functions provided to do this:
unsigned long htonl(unsigned long) unsigned short htons(unsigned short) unsigned long ntohl(unsigned long) unsigned short ntohs(unsigned short)