Home > front end >  Using Member Variable to set address.sin_port
Using Member Variable to set address.sin_port

Time:10-28

I am currently sitting on a small C project, where I am trying to write a class that implements tcp sockets, when I came across the following:

ServerSocket::ServerSocket(uint16_t port_) {
    struct sockaddr_in _address;
    uint16_t _port = port_;
    this->bindSocket();
}

int ServerSocket::bindSocket() {
    _address.sin_port = htons(_port);
    std::cout << _address.sin_port << std::endl;
}

Which prints "0" and doesn't work as expected, while the following works as expected:

ServerSocket::ServerSocket(uint16_t port_) {
    struct sockaddr_in _address;
    this->bindSocket(port_);
}

int ServerSocket::bindSocket(uint16_t port_) {
    _address.sin_port = htons(port_);
    std::cout << _address.sin_port << std::endl;
}

I don't understand how the first piece of code does not work and I really hope somebody can help me to understand.

CodePudding user response:

You have accidentally declared a variable, instead of initializing a member:

ServerSocket::ServerSocket(uint16_t port_) {
    struct sockaddr_in _address; // This is redundant
    uint16_t _port = port_; // <-- oopsie
    this->bindSocket(); // redundant this
}

It should be:

ServerSocket::ServerSocket(uint16_t port_) {
    _port = port_;
    this->bindSocket();
}

You can try to avoid situations like these in the future if you use a list initializer

ServerSocket::ServerSocket(uint16_t port_) : _port(port_)
{
    bindSocket();
}
  •  Tags:  
  • c
  • Related