[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 428
  • Last Modified:

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?
0
Tim Titus
Asked:
Tim Titus
1 Solution
 
Tim TitusCTOAuthor Commented:
Addendum: The SMTPPort variable should remain a DWORD, as it is being read from the registry elsewhere in the program.
0
 
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now