TCP socket listen - Unix

This is a discussion on TCP socket listen - Unix ; Can I listen connections coming from specific hosts or ports? For example: ----------------- int lstnfd, cnntfd; struct sockaddr_in saddr, daddr; int len; lstnfd = socket(AF_INET, SOCK_STREAM, 0); memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(80); saddr.sin_addr.s_addr = htol(INADDR_ANY); bind(lstnfd, ...

+ Reply to Thread
Results 1 to 2 of 2

Thread: TCP socket listen

  1. TCP socket listen

    Can I listen connections coming from specific hosts or ports?

    For example:
    -----------------

    int lstnfd, cnntfd;
    struct sockaddr_in saddr, daddr;
    int len;

    lstnfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(80);
    saddr.sin_addr.s_addr = htol(INADDR_ANY);

    bind(lstnfd, (struct sockaddr *) &saddr,sizeof(struct sockaddr));
    listen(lstnfd, 5);
    cnntfd = accept(lstnfd, (struct sockaddr *) &daddr, &len);
    /*
    ...
    */

    user$ netstat -a
    Proto Recv-Q Send-Q Local Address Foreign Address
    State
    tcp 0 0 *:www *:*
    LISTEN

    Here listen connection from any hosts and any ports.
    Can I restrict it, e.g. *:[6000-8000], or 192.168.1.*:*?
    How?
    -thx)

  2. Re: TCP socket listen

    On Mar 8, 4:13 am, Kurt wrote:
    > Can I listen connections coming from specific hosts or ports?
    >
    > For example:
    > -----------------
    >
    > int lstnfd, cnntfd;
    > struct sockaddr_in saddr, daddr;
    > int len;
    >
    > lstnfd = socket(AF_INET, SOCK_STREAM, 0);
    > memset(&saddr, 0, sizeof(saddr));
    > saddr.sin_family = AF_INET;
    > saddr.sin_port = htons(80);
    > saddr.sin_addr.s_addr = htol(INADDR_ANY);
    >
    > bind(lstnfd, (struct sockaddr *) &saddr,sizeof(struct sockaddr));
    > listen(lstnfd, 5);
    > cnntfd = accept(lstnfd, (struct sockaddr *) &daddr, &len);
    > /*
    > ...
    > */
    >
    > user$ netstat -a
    > Proto Recv-Q Send-Q Local Address Foreign Address
    > State
    > tcp 0 0 *:www *:*
    > LISTEN
    >
    > Here listen connection from any hosts and any ports.
    > Can I restrict it, e.g. *:[6000-8000], or 192.168.1.*:*?
    > How?
    > -thx)


    If you want to restrict IPs that connect, look into using /etc/
    hosts.deny if you're using linux (google or man). As for port, if you
    want to discriminate based on the clients port, you should accept()
    and then close the connection or continue based on the sin_port of the
    sockaddr passed to accept(). You can also look at sin_addr to check
    the ip as an alternative for /etc/hosts.deny

    -Tom

+ Reply to Thread