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

Posted on 2007-10-15
Last Modified: 2013-11-13
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:

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?
Question by:ttitus

    Author Comment

    Addendum: The SMTPPort variable should remain a DWORD, as it is being read from the registry elsewhere in the program.
    LVL 4

    Accepted Solution

    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,

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Suggested Solutions

    Title # Comments Views Activity
    has12 challenge 13 52
    linearIn  challenge 23 54
    scoresSpecial  challenge 13 34
    drawing animated level bar based on numbers 3 41
    There is an easy way, in .NET, to centralize the treatment of all unexpected errors. First of all, instead of launching the application directly in a Form, you need first to write a Sub called Main, in a module. Then, set the Startup Object to th…
    Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
    The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
    This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now