I need to do simple client program, when I add port number and client will be serch all services for this port. Now is problem with segmentation fault in if statement.
How to return all services? In my program it will be return just one, I think.
my code:
int main (int argc, char *argv[])
{
int sockfd, n,pol, s;
int numer;
char recvline[MAXLINE +1];
char p;
struct sockaddr_in servaddr;
struct servent *sp;
if (argc != 3)
err_sys("Aby uruchomić podaj: klient <Adres IP> <port>");
s = atoi(argv[2]);
if((sp = getservbyport(s,NULL)) == NULL)
{
printf("port (s): %d \n", s);
printf("port (sp): %d \n", sp->s_port); //segmentation fault
err_sys("problem with port");
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0)
err_sys("Blad utworzenia polaczenia");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = sp->s_port;
if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr)<=0)
err_sys_kom("Blad konwersji do adresu IP dla %s", argv[1]);
printf("%s", sp->s_name);
pol = connect(sockfd, (SA*) &servaddr, sizeof(servaddr));
if (pol < 0)
{
err_sys_kom("Blad polaczenie z serwerem");
close(sockfd);
exit(-1);
}
else
str_cli(stdin, sockfd , 1);
exit(0);
}
EDIT (in response to new new problem – see comments below):
You probably need to get a list of protocols and work with those in a loop. The contents of the loop should roughly be:
getprotoentgetservbyportEDIT (in response to new problem):
So your logic is to read
spONLY IFspisNULL. Obviously it will segfault.It should be:
But then you will point out another new problem:
Why is
spNULL?This could be because (as per the earlier version of my answer), you did an
atoion something which was not an integer. It could be because of any other reason. We can’t say because we don’t know what input you give.This following part of the answer was in response to an old problem that the OP asked in the same question, and has since then chosen to edit over it:
First of all: Since you’re using
getservbyport, you really should read about services, if you haven’t already.Now on to the error:
getservbyportis of type:You are passing
argv[2]which is of typechar *instead of anintforport.I believe the user inputs this as an argument in your program?
If you know that a
char *points to a set of characters which look like an integer, like “1024”, then you can convert it to an integer withatoi.Do this instead, on the line with the error, when calling
getservbyport, while making sure you’ve includedstdlib.h:If
argv[2]is NOT representable as an integer, you’ll get undefined behavior, so maybe, you’ll want to check this first.