码迷,mamicode.com
首页 > 其他好文 > 详细

epoll案例

时间:2016-02-03 00:11:42      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <string.h>

#include <iostream>

#include <fcntl.h>

#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define LOCAL_AF            AF_INET
#define LOCAL_IP            "192.168.11.128"
#define LOCAL_PORT          8090

using namespace std;

//
static int setSocketNonBlock(const int socketFd)
{
    int ret(0);

    int flags = fcntl(socketFd, F_GETFL, 0);
    if (-1 == flags)
    {
        perror("fcntl");
        return -1;
    }

    flags |= O_NONBLOCK;
    ret = fcntl(socketFd, F_SETFL, flags);
    if (-1 == ret)
    {
        perror("fcntl");
        return -1;
    }

    return 0;
}

// 禁用socket的linger功能
static int setSocketLingerOff(const int socketFd)
{
    int ret(0);

    struct linger lingerVal;
    lingerVal.l_onoff = 1;
    lingerVal.l_linger = 0;
    ret = setsockopt(socketFd, SOL_SOCKET, SO_LINGER, &lingerVal, sizeof(struct linger));
    if (0 != ret)
    {
        perror("setsockopt");
        return -1;
    }

    return 0;
}

static int create_and_bind()
{
    int ret(0);

    struct addrinfo hints;
    struct addrinfo * result, * nextRes;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;
    ret = getaddrinfo(NULL, "8090", &hints, &result);
    if (0 != ret)
    {
        perror("getaddrinfo");
        return -1;
    }

    int listenSocket(-1);
    for (nextRes = result; nextRes != NULL; nextRes = nextRes->ai_next)
    {
        /*
        char ipBuf[1024];
        switch(nextRes->ai_family)
        {
        case AF_INET:
            inet_ntop(AF_INET, &(((sockaddr_in *)(nextRes->ai_addr))->sin_addr), ipBuf, sizeof(ipBuf));
            break;
        case AF_INET6:
            inet_ntop(AF_INET6, &(((sockaddr_in6 *)(nextRes->ai_addr))->sin6_addr), ipBuf, sizeof(ipBuf));
            break;
        }
        cout << "ipBuf: " << ipBuf << endl;
        */
        listenSocket = socket(nextRes->ai_family, nextRes->ai_socktype, nextRes->ai_protocol);
        if (-1 == listenSocket)
        {
            perror("socket");
            continue;
        }

        ret = bind(listenSocket, nextRes->ai_addr, nextRes->ai_addrlen);
        if (0 != ret)
        {
            perror("bind");
            close(listenSocket);
            continue;
        }
        break;
    }

    if (nextRes == NULL)
    {
        perror("create_and bind");
        return -1;
    }

    freeaddrinfo(result);

    return listenSocket;
}

int main(int argc, char **argv)
{
    create_and_bind();

    return 0;
}

epoll案例

标签:

原文地址:http://www.cnblogs.com/itpoorman/p/5178774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!