Ntohl is used on sin_port and gets negative nubmers

I am trying to print the client port in my server application that is on C. But I get negative client port numbers, what a strange behavior: - / Does anyone have an idea where there might be a problem?
Part of my code causing the problem:

struct sockaddr_in client_address; int chosenPort = (int) ntohl(client_address.sin_port); pritf("Client port is %d, chosenPort"); 

I get the port as -2121400320.

+4
source share
2 answers

Use ntohs() instead - sin_port is a 16-bit value.

+6
source

First of all, you should use the ntohs function instead of ntohl. ntohs () returns a 16-bit port number and ntohl returns a 32-bit IP address

Now you can get client details using getpeername ()

Syntax:

 #include <sys/socket.h> struct sockaddr_in client_address; int getpeername(int sockfd, struct sockaddr *client, socklen_t *addrlen); 

You can find more information using the man command.

0
source

Source: https://habr.com/ru/post/1400537/


All Articles