1
votes

I have a server:

./server portNumber

I have a client:

./client serverIpAddress

I have only server Ip Address in the client. I want to connect to Server socket. But every time Server Port Number is different. How Can I connect to server socket with BSD Socket in the client? Is it impossible? Do I have to know server port number?

Simple Usage BSD Socket:

    int socket_desc;
    struct sockaddr_in server;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr(ipAddress);
    server.sin_family = AF_INET;
    server.sin_port = htons( ThisIsServerPortNumber );

    //Connect to remote server
    if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        puts("connect error");
        return 1;
    }
3
Where's your C code where you set up the socket? Your question is a bit unclear. Or do you want to find it from the command line?Will

3 Answers

1
votes

Pick a port number between 49152 and 65535 for development. If your idea is successful, you'll want to register a port number between 1024 and 49151. Port numbers from 0 to 1023 are well-known ports, e.g. port 80 is for HTTP servers.

The TCP Port Service Multiplexer protocol was intended to allow discovery of port numbers for TCP servers, but it's seldom used due to security concerns.

0
votes

The bind(2) system call is used to select a port number in a server. It has to be called before the listen(2) system call and after the socket(2) call.

It allows to specify, not only the port number the server is going to listen for connections, but also the ip address in case the host has several interfaces and you want only to accept connections in one of the interfaces.

0
votes

But every time Server Port Number is different. How Can I connect to server socket with BSD Socket in the client? … Do I have to know server port number?

Yes, you have to know it. Think: There can be many different server programs running on the server host, bound to many different ports. A client computer has no simple insight into the server host to see to which port the desired server program is bound. Thus, it is usual to use a preassigned port number in the server as well as in the client.