Reputation: 68
Hello i just write a quite big email server - client, it all works, exept the connection to the server
the problem is the port. i set the port on both (server - client) to 49255, but the connection is refused. when i try to print out the port, normally or with ntohl() the port is set to 0
client
void init_struct(struct sockaddr_in *adress, long unsigned int ip) {
memset(adress, 0, sizeof(struct sockaddr_in));
adress->sin_port = htonl(49255);
adress->sin_family = AF_INET;
adress->sin_addr.s_addr = INADDR_ANY;
print("Set port to %d\n", n adress->sin_port);
}
server
void init_struct(struct sockaddr_in* server) {
memset(server, 0, sizeof(struct sockaddr_in));
server->sin_addr.s_addr = INADDR_ANY;
server->sin_family = AF_INET;
server->sin_port = htonl(49255);
printf("Set port to %d\n", server->sin_port);
}
and to add something: the server - client is running on the same machine
the output is:
Set port to 0
Cant connect to server, please try again
: Connection refused
on the client side.
on the server side it also print "set port to 0"
Upvotes: 1
Views: 53
Reputation: 223689
The sin_port
field is 16 bits, but the htonl
function converts 32 bit values. So when you pass the value 49255, which in hex is 0x0000C067, you get back the value 0x67C00000. When this value is converted back to 16 bit, only the lower 16 bits are retained and you're left with 0.
You instead want to use htons
which is for 16 bit values.
server->sin_port = htons(49255);
Upvotes: 3