Created
January 9, 2012 10:37
-
-
Save hasantayyar/1582425 to your computer and use it in GitHub Desktop.
UDPListener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#define MYPORT 11000 | |
#define MAXBUFLEN 512 | |
extern "C" { | |
// yoksa derlemiyor | |
int main(void) | |
{ | |
int sockfd; | |
struct sockaddr_in my_addr; | |
struct sockaddr_in their_addr; | |
socklen_t addr_len; | |
int numbytes; | |
char buf[MAXBUFLEN]; | |
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { | |
perror("socket"); | |
exit(1); | |
} | |
my_addr.sin_family = AF_INET; | |
my_addr.sin_addr.s_addr = INADDR_ANY; | |
my_addr.sin_port = htons(MYPORT); | |
memset(&(my_addr.sin_zero), '\0', 8); | |
if (bind(sockfd, (struct sockaddr *)&my_addr, | |
sizeof(struct sockaddr)) == -1) { | |
perror("bind"); | |
exit(1); | |
} | |
addr_len = sizeof(struct sockaddr); | |
while(numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, | |
(struct sockaddr *)&their_addr, &addr_len) ) { | |
printf("got packet from %s\n",inet_ntoa(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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment