Skip to content

Instantly share code, notes, and snippets.

@ralight
Last active September 30, 2015 11:38
Show Gist options
  • Select an option

  • Save ralight/0d1d6cb4e353c075b152 to your computer and use it in GitHub Desktop.

Select an option

Save ralight/0d1d6cb4e353c075b152 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <fcntl.h>
#define BUF_SIZE 10000
uint8_t connack[] = {0x20, 0x02, 0x00, 0x00};
int socket_listen(void)
{
struct addrinfo hints;
struct addrinfo *ainfo;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = PF_INET;
hints.ai_flags = AI_PASSIVE;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(NULL, "1883", &hints, &ainfo);
int sock = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol);
int ss_opt = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &ss_opt, sizeof(ss_opt));
int opt;
fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, opt | O_NONBLOCK);
bind(sock, ainfo->ai_addr, ainfo->ai_addrlen);
listen(sock, SOMAXCONN);
freeaddrinfo(ainfo);
return sock;
}
int socket_accept(int listener)
{
int sock;
sock = accept(listener, NULL, 0);
int opt;
fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, opt | O_NONBLOCK);
return sock;
}
int main(int argc, char *argv[])
{
int listener;
int esock;
int client_sock;
struct epoll_event event;
struct epoll_event *events;
int count;
int i;
char buf[BUF_SIZE];
listener = socket_listen();
esock = epoll_create1(0);
event.data.fd = listener;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(esock, EPOLL_CTL_ADD, listener, &event);
events = calloc(100, sizeof(event));
while(1){
count = epoll_wait(esock, events, 100, -1);
for(i=0; i<count; i++){
if((events[i].events & EPOLLERR)
|| (events[i].events & EPOLLHUP)
|| (!(events[i].events & EPOLLIN))){
exit(1);
}else if(events[i].data.fd == listener){
client_sock = socket_accept(listener);
event.data.fd = client_sock;
event.events = EPOLLIN | EPOLLET;
epoll_ctl(esock, EPOLL_CTL_ADD, client_sock, &event);
write(client_sock, connack, 4);
}else{
read(events[i].data.fd, buf, BUF_SIZE);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment