Issue
I am using Linux Mint and I am trying to develop a server side application that will listen to a specific port. I tried setting the port to using htons(0)
but still same issue.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
float calculator(char *calculation);
extern int errno;
int main(int argc,char **argv)
{
int clientaddrlen, listenfd, connectfd, bytes_rcvd, listen_queue_size=1;
short int port_no;
char readBuff[1000];
struct sockaddr_in servaddr, clientaddr;
pid_t childpid;
int status;
char sendBuff[1025];
if(argc!=3){
printf("Usage Format: ./server -p <PortNumber>\n");
printf("Sample Run: ./server -p 2000\n");
exit(1);
}
port_no = atoi(argv[argc-1]);
printf("Server running at port #%d\n", port_no);
// Create server socket.
if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
fprintf(stderr, "Cannot create server socket! errno %i: %s\n",errno,strerror(errno));
exit(1);
}
printf("Server socket created\n");
// Bind (attach) this process to the server socket.
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port_no);
errno = bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
if(errno < 0){
printf("Server bind failure errno %i: %s\n",errno,strerror(errno));
exit(1);
}
Given that my code runs on other machines I suppose something is wrong with my system. The error I am getting is
Server bind failure errno -1: Unknown error -1
This is right after the bind syscall which for some reason returns -1 in my System. Is there something from my system that causes this issue?
Solution
I was using errorno wrong. It is set internally in the bind()
function and I need to set a different variable to store the return value of bind()
.
So after changing my code to :
int result = bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
if(result < 0)
{
printf("Server bind failure errno %i: %s\n",errno,strerror(errno));
exit(-1);
}
I found the true errno
which was 13.
Errorno 13 Stands for Permission denied
.
As it turns out in my system ports from under 1080
are reserved for root and this is why I was getting an error. While in other systems it has to be over 1024. I do not know why htons(0)
gave an error but when I changed my port to 2000
instead of 1025
it worked. In order to use ports under 1080 I had to run the app using sudo
.
Answered By - John Demetriou Answer Checked By - Dawn Plyler (WPSolving Volunteer)