Search
lxdream.org :: lxdream/src/ioutil.c
lxdream 0.9.1
released Jun 29
Download Now
filename src/ioutil.c
changeset 1077:136fc24d17ef
prev1021:848db285a184
author nkeynes
date Fri May 29 18:47:05 2015 +1000 (7 years ago)
permissions -rw-r--r--
last change Fix test case
file annotate diff log raw
nkeynes@998
     1
/**
nkeynes@1021
     2
 * $Id$
nkeynes@998
     3
 * 
nkeynes@998
     4
 * Network support functions
nkeynes@998
     5
 *
nkeynes@998
     6
 * Copyright (c) 2009 Nathan Keynes.
nkeynes@998
     7
 *
nkeynes@998
     8
 * This program is free software; you can redistribute it and/or modify
nkeynes@998
     9
 * it under the terms of the GNU General Public License as published by
nkeynes@998
    10
 * the Free Software Foundation; either version 2 of the License, or
nkeynes@998
    11
 * (at your option) any later version.
nkeynes@998
    12
 *
nkeynes@998
    13
 * This program is distributed in the hope that it will be useful,
nkeynes@998
    14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
nkeynes@998
    15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
nkeynes@998
    16
 * GNU General Public License for more details.
nkeynes@998
    17
 */
nkeynes@998
    18
nkeynes@998
    19
#include <string.h>
nkeynes@998
    20
#include <unistd.h>
nkeynes@998
    21
#include <sys/socket.h>
nkeynes@998
    22
#include <netinet/in.h>
nkeynes@998
    23
#include <arpa/inet.h>
nkeynes@998
    24
#include <errno.h>
nkeynes@1077
    25
#include "ioutil.h"
nkeynes@998
    26
nkeynes@1077
    27
int io_create_server_socket(const char *interface, int port )
nkeynes@998
    28
{
nkeynes@998
    29
    struct sockaddr_in sin;
nkeynes@998
    30
    int fd = socket(AF_INET, SOCK_STREAM, 0);
nkeynes@998
    31
    if( fd == -1 ) {
nkeynes@998
    32
        ERROR( "Failed to create TCP socket!" );
nkeynes@998
    33
        return -1;
nkeynes@998
    34
    }
nkeynes@998
    35
    
nkeynes@998
    36
    sin.sin_family = AF_INET;
nkeynes@998
    37
    sin.sin_addr.s_addr = 0;
nkeynes@998
    38
    sin.sin_port = htons(port);
nkeynes@998
    39
    
nkeynes@998
    40
    if( interface != NULL ) {
nkeynes@998
    41
        if( !inet_aton(interface, &sin.sin_addr) ) {
nkeynes@998
    42
            /* TODO: hostname lookup */
nkeynes@998
    43
        }
nkeynes@998
    44
    }
nkeynes@998
    45
nkeynes@998
    46
    if( bind( fd, (struct sockaddr *)&sin, sizeof(sin) ) != 0 ||
nkeynes@998
    47
            listen(fd, 5) != 0 ) {
nkeynes@998
    48
        close(fd);
nkeynes@998
    49
        ERROR( "Failed to bind port %d (%s)", port, strerror(errno) );
nkeynes@998
    50
        return -1;
nkeynes@998
    51
    }
nkeynes@998
    52
    return fd;
nkeynes@998
    53
}
nkeynes@998
    54
.