1
votes

I create a server at port 1234 of localhost. In the client code, I initiated a struct sockaddr_in server_addr and filled it with the server's IP address and port number. When I try to connect a client to the server, I get "Address already in use":

bind(client_sockfd, server_addr, sizeof server_addr)

So the OS thinks that I was trying to create another server socket with the same address and port number. In this case, how can I tell the OS that server_addr is the other endpoint I want to connect to and that it finds another port number for the client's socket?

2

2 Answers

3
votes

You need to use bind() only for the server and in the client use

int connect(int socket, const struct sockaddr *address, socklen_t address_len);.

See this tutorial for information about sockets in Linux:

http://www.linuxhowtos.org/C_C++/socket.htm

2
votes

you use connect(client_sockfd, server_addr, sizeof(..)) to tell OS that my client socket should connect to this server address.

If it is UDP socket, you can also use sendto(client_sockfd, ... server_addr) call to specify that the packet should go to this server address.