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
- 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> 25}if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1) {perror("socket");exit(1);}my_addr.sin_family = AF_INET; // host byte ordermy_addr.sin_port = h<strong>to</strong>ns(MYPORT); // short, network byte ordermy_addr.sin_addr.s_addr = INADDR_ANY; // au<strong>to</strong>matically fill with my IPmemset(&(my_addr.sin_zero), ’\0’, 8); // zero the rest of the structif (bind(sockfd, (struct sockaddr *)&my_addr,sizeof(struct sockaddr)) == -1) {perror("bind");exit(1);}addr_len = sizeof(struct sockaddr);if ((numbytes=recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,(struct sockaddr *)&their_addr, &addr_len)) == -1) {perror("recvfrom");exit(1);}printf("got packet from %s\n",inet_n<strong>to</strong>a(their_addr.sin_addr));printf("packet is %d bytes long\n",numbytes);buf[numbytes] = ’\0’;printf("packet contains \"%s\"\n",buf);close(sockfd);return 0;Notice that in our call <strong>to</strong> socket() we’re finally using SOCK_DGRAM. Also, note that there’s noneed <strong>to</strong> listen() or accept(). This is one of the perks of using unconnected datagram sockets!Next comes the source for talker.c 15 :/*** talker.c -- a datagram "client" demo*/#include #include #include #include #include #include #include #include #include #include #define MYPORT 4950// the port users will be connecting <strong>to</strong>int main(int argc, char *argv[]){int sockfd;struct sockaddr_in their_addr; // connec<strong>to</strong>r’s address informationstruct hostent *he;int numbytes;if (argc != 3) {fprintf(stderr,"usage: talker hostname message\n");exit(1);15 http://beej.us/guide/bgnet/examples/talker.c