0

I am writing a small tcp server based on the example listed below , from here.

#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MY_SOCK_PATH "/somepath"
#define LISTEN_BACKLOG 50

#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

int
main(int argc, char *argv[])
{
    int sfd, cfd;
    struct sockaddr_un my_addr, peer_addr;
    socklen_t peer_addr_size;

   sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sfd == -1)
        handle_error("socket");

   memset(&my_addr, 0, sizeof(struct sockaddr_un));
                        /* Clear structure */
    my_addr.sun_family = AF_UNIX;
    strncpy(my_addr.sun_path, MY_SOCK_PATH,
            sizeof(my_addr.sun_path) - 1);

   if (bind(sfd, (struct sockaddr *) &my_addr,
            sizeof(struct sockaddr_un)) == -1)
        handle_error("bind");

   if (listen(sfd, LISTEN_BACKLOG) == -1)
        handle_error("listen");

   /* Now we can accept incoming connections one
       at a time using accept(2) */

   peer_addr_size = sizeof(struct sockaddr_un);
    cfd = accept(sfd, (struct sockaddr *) &peer_addr,
                 &peer_addr_size);
    if (cfd == -1)
        handle_error("accept");

   /* Code to deal with incoming connection(s)... */

   /* When no longer required, the socket pathname, MY_SOCK_PATH
       should be deleted using unlink(2) or remove(3) */
}

When using accept() to open a new connection, is it possible to only accept connections from whitelisted IP-addresses OR reject blacklisted IP-addresses somehow?

The only technique I have found so far is to first accept, check the address, and then close() afterwards if its not an approved address.

Any suggestions?

Barath Ravikumar
  • 5,658
  • 3
  • 23
  • 39
agnsaft
  • 1,791
  • 7
  • 30
  • 49
  • possible duplicate of [Server socket - accept connections only from IP addresses in the whitelist](http://stackoverflow.com/questions/9696618/server-socket-accept-connections-only-from-ip-addresses-in-the-whitelist) – Nick Mar 21 '13 at 14:10

1 Answers1

6

With the POSIX API and TCP, you have to do accept() to lookup a clients address, and then you are free to close, receive, send or ignore.

Normally you would use the operating systems firewall for a task like this.

And remember just ignoring certain clients will not add security, as you are still susceptible to man in the middle, replay and sniffing attacks.

jbr
  • 6,198
  • 3
  • 30
  • 42