libevent-test.c

001. 
002. #include <stdio.h>
003. #include <stdlib.h>
004. #include <syslog.h>
005. #include <errno.h>
006. #include <unistd.h>
007. #include <string.h>
008. 
009. /* sockets */
010. #include <sys/types.h>
011. #include <sys/socket.h>
012. 
013. /* for non blocking */
014. #include <fcntl.h>
015. 
016. #include <netinet/in.h>
017. #include <arpa/inet.h>
018. 
019. #include <pthread.h>
020. 
021. /* for libevent */
022. #include <event.h>
023. 
024. // #define MAKE_UDP 1
025. 
026. void readEv(int fd, short event, void* arg) {
027. 	int len;
028. 	char *buf = malloc(255);
029. 	struct event *ev = arg;
030. #ifdef MAKE_UDP
031. 	int l = sizeof(struct sockaddr);
032. 	struct sockaddr_in cAddr;
033. #endif
034. 	
035. 	printf("DNS_read called with %s fd: %d, event: %d\n",
036. 		event_get_method(), fd, event);
037. 
038. #ifdef MAKE_UDP
039. 	len = recvfrom(fd, buf, 254, 0, (struct sockaddr*)&cAddr, &l);
040. #else
041. 	len = recv(fd, buf, 254, 0);
042. #endif
043. 
044. 	if (len == -1) {
045. #ifdef MAKE_UDP
046. 		perror("recvfrom()");
047. #else
048. 		perror("recv");
049. #endif
050. 		return;
051. 	} else if (len == 0) {
052. 		printf("Connection Closed\n");
053. 		return;
054. 	}
055. 	
056. 	buf[len] = '\0';
057. 	
058. 	printf("READ: %s\n", buf);
059. }
060. 
061. int main() {
062. 	int sock;
063. 	int yes = 1;
064. 	int len = sizeof(struct sockaddr);
065. 	struct sockaddr_in addr;
066. 
067. #ifdef MAKE_UDP
068. 	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
069. #else
070. 	if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
071. #endif
072. 		perror("socket");
073. 		return 1;
074. 	}
075. 	
076. 	if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) {
077. 		perror("setsockopt");
078. 		return 1;
079. 	}
080. 	
081. 	addr.sin_family = AF_INET;
082. 	addr.sin_port = htons(5555);
083. 	addr.sin_addr.s_addr = INADDR_ANY;
084. 	bzero(&(addr.sin_zero), 8);
085. 	
086. 	if (bind(sock, (struct sockaddr*)&addr, len) < 0) {
087. 		perror("bind");
088. 		return 1;
089. 	}
090. 	
091. #ifndef MAKE_UDP
092. 	if (listen(sock, 16) < 0) {
093. 		perror("listen");
094. 		return 1;
095. 	}
096. #endif
097. 
098. 	printf("Listening now...\n");
099. 	
100. 	struct event ev;
101. 	
102. 	event_init();
103. 	
104. 	event_set(&ev, sock, EV_READ | EV_PERSIST, readEv, &ev);
105. 	
106. 	event_add(&ev, NULL);
107. 	
108. 	event_dispatch();
109. 	
110. 	printf("Done!\n");
111. 	return 1;
112. }
113. 
114. 
  • Disclaimer
  • The ideas and opinions expressed here are mine.
  • I'm a Linux and BSD user, and lean heavily toward the use of OSS vs certain other commercial solutions.

View the Ninja's profile on LinkedIn

:= RSS =: