Boo
Boo

Reputation: 377

C programming how to change the port a socket is connected to

So this is a homework assignment expanding of this LinuxHowTo page . I'm tasked with creating a client and server. The server can have up to 5 connections to clients, and must remain open for new connections to clients when not full. Once a client connects and the server accepts. I run a fork() in the server, and then from the child I send the data back and forth between server and client.

    //accept function will take next connection from listen queue for processing
    //or it will block the process until a connection request arrives
    //third parameter identifies client can be null to accept any request from any machine
    newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);

The problem is that the child uses the same port as the parent, and so I can't make anymore connections to the parent.
Here's what i tried to do to change the port the client and server are communicating on.

However I keep getting connection the error when trying to connect from client.

//call connect return 0 for success and -1 for error
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ 
    fprintf(stderr,"ERROR connecting to server\n");
    //remove the new file 
    remove(newFileName);
    exit(1);
}

Upvotes: 0

Views: 3646

Answers (1)

David Schwartz
David Schwartz

Reputation: 182847

Just don't call bind in the client. When you call connect in the client, specify the IP and port that the server is listening on. This will cause the implementation to assign each client a unique source port to use.

The problem is that the child uses the same port as the parent, and so I can't make anymore connections to the parent.

You can make many outbound connections with the same destination port because they'll have different source ports. And, of course, a server can accept many connections with the same destination port.

Upvotes: 4

Related Questions