i'm pretty confused about some weird behavior i'm seeing with the
socket routines on a couple hamm machines.  i've written a simple dumb
server to demonstrate the behavior, and i'll attach it below.

basically, it opens a socket and tries to bind it to a specific port.
the wierd thing is that bind doesn't care if i try to bind to a
privileged port (numbered less than 1024).  the same code compiled
and run on a solaris box results in an error generated by the call to
bind() -- with errno set to EACCES, i believe.

the weirdest thing is that the socket doesn't seem to be actually
bound when i run it under linux, regardless of whether or not the port
i try to use is privileged or not.  i extended the code to actually
bind to port 23, listen on it, and go into an accept loop.  the code
runs to the accept loop without errors, but telnet connections still
seem to go to the right place (i.e. telnetd).

can anyone spot what i'm doing wrong?  anyone care to try this on
their hamm box?  thanks.

-alan

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>


#define DS_DEFAULTPORT 9999
#define USAGE "Usage: %s [<port>]\n"

int
main(int argc, char **argv)
{
  int serverSock;
  struct sockaddr_in serverSockName;
  int port;
  struct protoent *proto;

  if (argc > 2) {
    fprintf(stderr, USAGE, argv[0]);
    exit(1);
  }

  if (argc == 2) {
    if (sscanf(argv[1], "%d", &port) != 1) {
      fprintf(stderr, USAGE, argv[0]);
      exit(1);
    }
  }
  else {
    port = DS_DEFAULTPORT;
  }

  fprintf(stderr, "using port %d\n", port);

  /* 6 == protocol no. for tcp */
  serverSock = socket(AF_INET, SOCK_STREAM, 6);
  if (serverSock == -1) {
    perror("socket");
    exit(1);
  }

  serverSockName.sin_family = AF_INET;
  serverSockName.sin_addr.s_addr = INADDR_ANY;
  serverSockName.sin_port = port;
  if (bind(serverSock, (struct sockaddr *)&serverSockName,
           sizeof (struct sockaddr)) != 0) {
    perror("bind");
    exit(1);
  }

  fprintf(stderr, "socket bound\n");

  return(0);
}

Reply via email to