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...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 24}their_addr.sin_family = AF_INET; // host byte ordertheir_addr.sin_port = h<strong>to</strong>ns(PORT); // short, network byte ordertheir_addr.sin_addr = *((struct in_addr *)he->h_addr);memset(&(their_addr.sin_zero), ’\0’, 8); // zero the rest of the structif (connect(sockfd, (struct sockaddr *)&their_addr,sizeof(struct sockaddr)) == -1) {perror("connect");exit(1);}if ((numbytes=recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {perror("recv");exit(1);}buf[numbytes] = ’\0’;printf("Received: %s",buf);close(sockfd);return 0;Notice that if you don’t run the server before you run the client, connect() returns “Connectionrefused”. Very useful.5.3. Datagram <strong>Sockets</strong>I really don’t have that much <strong>to</strong> talk about here, so I’ll just present a couple of sample programs:talker.c and listener.c.listener sits on a machine waiting for an incoming packet on port 4950. talker sends a packet<strong>to</strong> that port, on the specified machine, that contains whatever the user enters on the command line.Here is the source for listener.c 14 :/*** listener.c -- a datagram sockets "server" demo*/#include #include #include #include #include #include #include #include #include #define MYPORT 4950#define MAXBUFLEN 100// the port users will be connecting <strong>to</strong>int main(void){int sockfd;struct sockaddr_in my_addr; // my address informationstruct sockaddr_in their_addr; // connec<strong>to</strong>r’s address informationsocklen_t addr_len;int numbytes;char buf[MAXBUFLEN];14 http://beej.us/guide/bgnet/examples/listener.c

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

Saved successfully!

Ooh no, something went wrong!