Hi I have written the following code but when I run it, it fails to bind every time, any ideas why?

int main(int argc, char *argv[]) {
  
  int port = 1080;
  int lsd, sd;
  struct sockaddr_in serv_addr, remote_addr;
  socklen_t remote_len;
  
  if(argc <  2 || argc > 2) {
    printf("Syntax is: %s Directory.\n", argv[0]);
    exit (1);
  }
  
  if(chdir(argv[1]) == -1){ 
    printf("Cannot change to directory %s.\n",argv[1]);
    exit (2);
  }
  
  if(lsd = socket(PF_INET, SOCK_STREAM, 0) < 0){
    printf("Cannot create socket.\n");
    exit (3);
  }
  
  bzero((char *) &serv_addr, sizeof(serv_addr)); //bzero() returns no value
   
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(port);
   
  if (bind(lsd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
    printf("Error binding socket to port %d.\n", port);
    exit (4);
  }
  
  if (listen(lsd, 5) == -1) {
    printf("Error listening on socket.\n");
    exit (5);
  }
  
  remote_len = sizeof(remote_addr);
  
  if (sd = accept(lsd, (struct sockaddr *) &remote_addr, &remote_len) < 0) {
    printf("Error accepting connection.\n");
    exit (6);
  }
  
  write(sd, "HELLO WORLD", 12);
  close(sd);
  close(lsd);
  return 0;
}

Thanks

Line 26

serv_addr.sin_addr.s_addr = INADDR_ANY;

Should be

serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

If that fails then try a larger port number like 50000.

Edited 5 Years Ago by gerard4143: n/a

Try the code below

int main(int argc, char *argv[]) 
{
  
  int port = 1080;
  int lsd, sd;
  struct sockaddr_in serv_addr, remote_addr;
  socklen_t remote_len;
  
  if(argc <  2 || argc > 2) {
    printf("Syntax is: %s Directory.\n", argv[0]);
    exit (1);
  }
  
  if(chdir(argv[1]) == -1){ 
    printf("Cannot change to directory %s.\n",argv[1]);
    exit (2);
  }
  
  if((lsd = socket(PF_INET, SOCK_STREAM, 0) < 0)){
    printf("Cannot create socket.\n");
    exit (3);
  }
  
  bzero((char *) &serv_addr, sizeof(serv_addr)); 
   
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(port);
   
  if (bind(lsd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
    printf("Error binding socket to port %d.\n", port);
    exit (4);
  }
  
  if (listen(lsd, 5) == -1) {
    printf("Error listening on socket.\n");
    exit (5);
  }
  
  remote_len = sizeof(remote_addr);
  
  if ((sd = accept(lsd, (struct sockaddr *) &remote_addr, &remote_len) < 0)) {
    printf("Error accepting connection.\n");
    exit (6);
  }
  
  write(sd, "HELLO WORLD", 12);
  close(sd);
  close(lsd);
  return 0;
}

OK with perror() I get error number 88: Socket operation on non-socket

Edit: Nevermind, sorted it

Edited 5 Years Ago by fg_aa_c: n/a

This article has been dead for over six months. Start a new discussion instead.