C__Package Unix Socket

参考AUPE封的

#include "xsock.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>

int setSockAddr(struct sockaddr_in *addr, const int family, const char *host, const int port)
{
    if ( ! (addr != NULL && host != NULL && port > 0) )
        return -1;
    addr->sin_family = family;  //  AF_INET
    addr->sin_addr.s_addr = inet_addr(host);
    addr->sin_port = htons(port);
    return 0;
}

int initServerSock(const int type, const struct sockaddr_in *addr, int lsn)
{
    int fd = -1;
    int err = 0;
    if ((fd = socket(addr->sin_family, type, 0)) < 0)
        return -1;

    if (bind(fd, (struct sockaddr *)addr, sizeof(*addr)) < 0)
    {
        err = errno;
        goto errout;
    }

    if (type == SOCK_STREAM || type == SOCK_SEQPACKET)
    {
        if (listen(fd, lsn) < 0)
        {
            err = errno;
            goto errout;
        }
    }
    
    return fd;

errout:
    close(fd);
    errno = err;
    printf("%d : %s\n",errno,strerror(errno));
    return -1;
}

int connect_retry(const int fd, const struct sockaddr_in *addr)
{
    int mxaSleep = 64;
    int nsec;

    for (nsec = 1; nsec <= mxaSleep; nsec <<=1)
    {
        if (connect(fd, (struct sockaddr *)addr, sizeof(*addr)) == 0)
        {
            return 0;
        }
        sleep(nsec);
    }
    return -1;
}

你可能感兴趣的:(C++,c,unix,socket,C#)