13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 23}}exit(0);}close(new_fd);return 0;// parent doesn’t need thisIn case you’re curious, I have the code in one big main() function for (I feel) syntactic clarity.Feel free <strong>to</strong> split it in<strong>to</strong> smaller functions if it makes you feel better.(Also, this whole sigaction() thing might be new <strong>to</strong> you–that’s ok. The code that’s there isresponsible for reaping zombie processes that appear as the fork()ed child processes exit. If youmake lots of zombies and don’t reap them, your system administra<strong>to</strong>r will become agitated.)You can get the data from this server by using the client listed in the next section.5.2. A Simple Stream ClientThis guy’s even easier than the server. All this client does is connect <strong>to</strong> the host you specifyon the command line, port 3490. It gets the string that the server sends.The client source 13 :/*** client.c -- a stream socket client demo*/#include #include #include #include #include #include #include #include #include #define PORT 3490 // the port client will be connecting <strong>to</strong>#define MAXDATASIZE 100 // max number of bytes we can get at onceint main(int argc, char *argv[]){int sockfd, numbytes;char buf[MAXDATASIZE];struct hostent *he;struct sockaddr_in their_addr; // connec<strong>to</strong>r’s address informationif (argc != 2) {fprintf(stderr,"usage: client hostname\n");exit(1);}if ((he=gethostbyname(argv[1])) == NULL) {herror("gethostbyname");exit(1);}// get the host infoif ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {perror("socket");exit(1);}13 http://beej.us/guide/bgnet/examples/client.c

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!