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

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

Set both LOCAL and TARGET port on socket... (C not C++ - Windows XP Pro - LCC Compiler)

Hi everyone!
                 I have written a socket server program that is working just fine. However, I want to be able to go OUT through my firewall on one specific port "6190" and hit the target server program on port "62781".
I can hit the target server program on port "62781" fine and establish a working connection great but I want to go out on this specific local port "6190" and not just whatever port Windows slaps me on!

Hope someone has a clue as I seem to have exhausted my search words in google.

Thanks, Ralph.

0
RalphG
Asked:
RalphG
  • 2
1 Solution
 
RalphGAuthor Commented:
Oh maybe this will help, it's what I have that's working but without local port specification:

client_s = socket(AF_INET, SOCK_STREAM, 0);

server_addr.sin_family      = AF_INET;                      // Address family to use
server_addr.sin_port        = htons(PORT_NUM);        // Port num to use
server_addr.sin_addr.s_addr = inet_addr(IP_ADDR); // IP address to use

if (connect(client_s, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0){
         printf("Connected to Server Program\n"); ...
0
 
alexscheeleCommented:
To do this you would need to bind your socket to a local port.


client_s = socket(AF_INET, SOCK_STREAM, 0);

local_addr.sin_family = AF_INET;                // Address family to use
local_addr.sin_port = htons(portnum);        // Local port

if (bind(client_s, (struct sockaddr *)&local_addr, sizeof(local_addr)) != 0) {
    // bind failed
    return(NULL);
}

server_addr.sin_family      = AF_INET;                      // Address family to use
server_addr.sin_port        = htons(PORT_NUM);        // Port num to use
server_addr.sin_addr.s_addr = inet_addr(IP_ADDR); // IP address to use

if (connect(client_s, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0){
         printf("Connected to Server Program\n"); ...
0
 
RalphGAuthor Commented:
Alexscheele you are a life saver!

Thanks for your quick reply and for taking the time to actually write a coded example.
I changed my code to include the initial "bind" and it worked a treat.
I checked the lot with netstat and my server program also returns the port that the client left on and all is well.

Cannot thank you enough but here's another one anyway.

Thanks Ralph.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

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