Reputation: 17
i have this programm which should only bind a socket to a port and i always get
failure while binding.
I can compile it without a problem.
should i add something to the servAddr
?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Practical.h"
int main(int argc , char* argv[]){
if(argc!=2){
printf("Parameters : <server Port>");
}
in_port_t servPort=atoi(argv[1]);
int servSock;
if(servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)<0){
printf("error socket");
}
struct sockaddr_in servAddr;
memset(&servAddr,0,sizeof(servAddr));
servAddr.sin_family=AF_INET;
servAddr.sin_addr.s_addr=htonl(INADDR_ANY);
servAddr.sin_port=htons(servPort);
if(bind(servSock,(struct sockaddr*) &servAddr,sizeof(servAddr)) < 0){
printf("failure while binding");
}
}
Upvotes: 2
Views: 108
Reputation: 8209
=
has priority lower than <
, add extra braces:
if((servSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0){
printf("error socket");}
Without these braces servSock
is 1
or 0
, that is definitely not what you want. Also note that without priviledges you can not bind to ports lower that 1024.
Upvotes: 6