pravu pp
pravu pp

Reputation: 882

How to make system choose port no for me in socket programming?

How to make system choose port no for me on the connect() call in c below is my code where i have used 5000 as port no the problem is every time i have to keep on changing the port no because it is throwing exception as ?

listen: Address already in use

How to get rid of this i want to fix the port no without making change in future is it possible?

int main(void)
{
    int sockfd = 0,n = 0;
    char recvBuff[1024];
    struct sockaddr_in serv_addr;
    memset(recvBuff, '0' ,sizeof(recvBuff));
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
        {
            printf("\n Error : Could not create socket \n");
            return 1;
        }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(5000);  //how to skip Address already in use?

    serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
        {
            printf("\n Error : Connect Failed \n");
            return 1;
        }

Upvotes: 2

Views: 279

Answers (1)

Sunil Bojanapally
Sunil Bojanapally

Reputation: 12658

Check in IANA Port number Listing, pick the which is not assigned or registered a prior. In your case port number 5000 is a TCP port already registered and used for commplex-main.

Note: Do not choose ports between 0 - 1023 as they are used by system processes.

Upvotes: 1

Related Questions