How to set a winsock port correctly in C/C++

If I use the "getservbyname", I can correctly assign my Winsock port to SMTP:
ServEntry = getservbyname("smtp", "tcp");
if (ServEntry != NULL)
{
    sin.sin_port = ServEntry->s_port;
}
If I want to set this port to a different port number, how do I set it?  I have a situation where a the SMTP port is different (for security purposes), and I need to use a variable:

DWORD  SMTPPort=25;
sin.sin_port = SMTPPort;

Do I need to use htons(SMTPPort)?  Will there be conversion problems for sin_port because it's a 16bit field, or do I just typecast it to fix the compile error?
Tim TitusCTOAsked:
Who is Participating?
 
bdunz19Commented:
Wow, I can't believe no one has replied to this yet.

What you have above almost works. Try this instead:

sin.sin_port = htons((USHORT)SMTPPort);

SMTPPort can be of DWORD type as I do the same thing on my servers as what you're doing (pulling the port from the registry).

Good luck,
Brandon
0
 
Tim TitusCTOAuthor Commented:
Addendum: The SMTPPort variable should remain a DWORD, as it is being read from the registry elsewhere in the program.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.